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

若要將服務裝載於 Managed 應用程式中,請將服務的程式碼嵌入 Managed 應用程式的程式碼,再以命令式程式碼或透過組態以宣告方式定義服務的端點 (亦可使用預設端點),然後建立 ServiceHost 的執行個體。

若要開始接收訊息,請呼叫 Open 上的 ServiceHost。 這樣會建立並開啟服務的接聽項。 用這種方式來裝載服務一般稱為「自我裝載」,因為 Managed 應用程式會自行執行裝載工作。 若要關閉服務,請呼叫 CommunicationObject.Close 上的 ServiceHost

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

將服務裝載在 Managed 應用程式中是最有彈性的選項,因為這麼做只需要部署最基本基礎結構。 如需在受控應用程式中裝載服務的詳細資訊,請參閱在受控應用程式中裝載

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

建立自我裝載服務

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

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

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

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

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

    提示

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

  3. 按兩下 [方案總管] 中的 [Program.cs] 或 [Module1.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[])。 啟用中繼資料發行,然後呼叫 OpenServiceHost 方法初始化服務並準備接收訊息。

    // 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 {0}", 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. 按兩下 [我的服務專案] 節點底下的 [SayHello]。 在 [要求] 清單中的 [值] 欄內輸入您的名稱,然後按一下 [叫用]

    回覆訊息隨即出現在 [回應] 清單中。

範例

下列範例會建立 ServiceHost 物件來裝載型別為 HelloWorldService 的服務,然後呼叫 Open 上的 ServiceHost 方法。 基底位址由程式碼提供、中繼資料發行已啟用,而且將使用預設端點。

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 {0}", 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

另請參閱