共用方式為


如何:在受控應用程式中裝載 WCF 服務

若要在受控應用程式內裝載服務,請在 Managed 應用程式程式代碼內嵌服務的程式代碼、在程式碼中以命令方式定義服務的端點、以宣告方式透過組態或使用預設端點,然後建立 ServiceHost實例。

若要開始接收訊息,請在 ServiceHost上呼叫 Open。 這會建立並開啟服務的接聽程式。 以這種方式裝載服務通常稱為「自我裝載」,因為受控應用程式正在自行執行裝載工作。 若要關閉服務,請在 ServiceHost上呼叫 CommunicationObject.Close

服務也可以裝載在受控 Windows 服務、Internet Information Services (IIS)或 Windows Process Activation Service (WAS) 中。 如需有關服務主機選項的詳細資訊,請參閱 託管服務

在受控應用程式中裝載服務是最具彈性的選項,因為它需要最少的基礎結構才能部署。 如需有關受控應用程式中的托管服務的更多資訊,請參閱 受控應用程式中的托管

在主控台應用程式中,下列程式示範如何實作自行裝載的服務。

建立自我託管服務

  1. 建立新的主控台應用程式:

    1. 開啟 Visual Studio,然後從 檔案 功能表中選取 新增>專案

    2. 在 [已安裝的範本] 清單中,選取 [Visual C#] 或 [Visual Basic],然後選取 [Windows Desktop]。

    3. 選取 主控台應用程式範本。 在 名稱 方塊中輸入 SelfHost,然後選擇 確定

  2. 在 [方案總管] 中,以滑鼠右鍵按兩下 SelfHost,然後選取 [[新增參考]。 從 [.NET] 索引標籤選取 [System.ServiceModel],然後選擇 [確定]。

    小提示

    如果看不到 [方案總管] 視窗,請從 [檢視] 功能表中選取 [方案總管]

  3. 方案總管 中按兩下 Program.csModule1.vb 以在程式碼視窗中開啟它,如果尚未開啟。 在檔案頂端新增下列語句:

    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    
  4. 定義及實作服務合約。 此範例會定義 HelloWorldService,根據服務的輸入傳回訊息。

    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }
    
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }
    
    <ServiceContract()>
    Public Interface IHelloWorldService
        <OperationContract()>
        Function SayHello(ByVal name As String) As String
    End Interface
    
    Public Class HelloWorldService
        Implements IHelloWorldService
    
        Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello
            Return String.Format("Hello, {0}", name)
        End Function
    End Class
    

    備註

    如需如何定義及實作服務介面的詳細資訊,請參閱 如何:定義服務合約如何:實作服務合約

  5. Main 方法頂端,使用服務的基位址建立 Uri 類別的實例。

    Uri baseAddress = new Uri("http://localhost:8080/hello");
    
    Dim baseAddress As Uri = New Uri("http://localhost:8080/hello")
    
  6. 建立 ServiceHost 類別的實體,將代表服務類型和基位址統一資源識別元 (URI) 的 Type 傳遞至 ServiceHost(Type, Uri[])。 啟用元數據發佈,然後在 ServiceHost 上呼叫 Open 方法來初始化服務,並準備接收訊息。

    // Create the ServiceHost.
    using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
    {
        // Enable metadata publishing.
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
        host.Description.Behaviors.Add(smb);
    
        // Open the ServiceHost to start listening for messages. Since
        // no endpoints are explicitly configured, the runtime will create
        // one endpoint per base address for each service contract implemented
        // by the service.
        host.Open();
    
        Console.WriteLine($"The service is ready at {baseAddress}");
        Console.WriteLine("Press <Enter> to stop the service.");
        Console.ReadLine();
    
        // Close the ServiceHost.
        host.Close();
    }
    
    ' Create the ServiceHost.
    Using host As New ServiceHost(GetType(HelloWorldService), baseAddress)
    
        ' Enable metadata publishing.
        Dim smb As New ServiceMetadataBehavior()
        smb.HttpGetEnabled = True
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
        host.Description.Behaviors.Add(smb)
    
        ' Open the ServiceHost to start listening for messages. Since
        ' no endpoints are explicitly configured, the runtime will create
        ' one endpoint per base address for each service contract implemented
        ' by the service.
        host.Open()
    
        Console.WriteLine("The service is ready at {0}", baseAddress)
        Console.WriteLine("Press <Enter> to stop the service.")
        Console.ReadLine()
    
        ' Close the ServiceHost.
        host.Close()
    
    End Using
    

    備註

    此範例會使用預設端點,而且此服務不需要任何組態檔。 如果未設定任何端點,則運行時間會針對服務所實作的每個服務合約,為每個基位址建立一個端點。 如需預設端點的詳細資訊,請參閱 簡化的組態WCF 服務的簡化組態

  7. Ctrl+Shift+B 建置解決方案。

測試服務

  1. 按 Ctrl+F5 以執行服務。

  2. 開啟 WCF 測試用戶端

    小提示

    若要開啟 WCF 測試用戶端,請開啟 Visual Studio 的開發人員命令提示字元,然後執行 WcfTestClient.exe

  3. 從 [檔案] 功能表中選取 [新增服務]。

  4. 在位址方塊中輸入 http://localhost:8080/hello,然後按下 [確定]

    小提示

    請確定服務正在執行,否則此步驟會失敗。 如果您已變更程式代碼中的基位址,請使用此步驟中修改的基位址。

  5. My Service Projects 節點下,按兩下 SayHello。 在 [要求] 清單中的 [] 欄位中輸入您的名稱,然後按一下 [叫用]。

    回復訊息會出現在 回應 清單中。

範例

下列範例會建立 ServiceHost 對象來裝載類型為 HelloWorldService的服務,然後在 ServiceHost上呼叫 Open 方法。 在程式代碼中提供基位址、啟用元數據發佈,並使用預設端點。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace SelfHost
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }

    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/hello");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                host.Open();

                Console.WriteLine($"The service is ready at {baseAddress}");
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
    }
}
Imports System.ServiceModel
Imports System.ServiceModel.Description

Module Module1

    <ServiceContract()>
    Public Interface IHelloWorldService
        <OperationContract()>
        Function SayHello(ByVal name As String) As String
    End Interface

    Public Class HelloWorldService
        Implements IHelloWorldService

        Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello
            Return String.Format("Hello, {0}", name)
        End Function
    End Class

    Sub Main()
        Dim baseAddress As Uri = New Uri("http://localhost:8080/hello")

        ' Create the ServiceHost.
        Using host As New ServiceHost(GetType(HelloWorldService), baseAddress)

            ' Enable metadata publishing.
            Dim smb As New ServiceMetadataBehavior()
            smb.HttpGetEnabled = True
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
            host.Description.Behaviors.Add(smb)

            ' Open the ServiceHost to start listening for messages. Since
            ' no endpoints are explicitly configured, the runtime will create
            ' one endpoint per base address for each service contract implemented
            ' by the service.
            host.Open()

            Console.WriteLine("The service is ready at {0}", baseAddress)
            Console.WriteLine("Press <Enter> to stop the service.")
            Console.ReadLine()

            ' Close the ServiceHost.
            host.Close()

        End Using

    End Sub

End Module

另請參閱