分享方式:


自我裝載

自我裝載範例會示範如何在主控台應用程式中實作自我裝載的服務。 這個範例是根據使用者入門。 服務的組態檔已經從 Web.config 重新命名為 App.config,並且修改為設定主機使用的基底位址。 服務的原始程式碼已經修改為實作靜態 Main 函式,這個函式會建立和開啟提供已設定之基底位址的服務主機。 服務實作已經修改為將每個作業的輸出寫入至主控台。 除了設定服務的正確端點位址外,用戶端未經過修改。

注意

此範例的安裝程序與建置指示位於本主題的結尾。

此範例會實作靜態的 main 函式,以便為指定的 ServiceHost 型別建立 CalculatorService,如下列範例程式碼所示。

// Host the service within this EXE console application.
public static void Main()
{
    // Create a ServiceHost for the CalculatorService type.
    using (ServiceHost serviceHost =
           new ServiceHost(typeof(CalculatorService)))
    {
        // Open the ServiceHost to create listeners
        // and start listening for messages.
        serviceHost.Open();

        // The service can now be accessed.
        Console.WriteLine("The service is ready.");
        Console.WriteLine("Press <ENTER> to terminate service.");
        Console.WriteLine();
        Console.ReadLine();
    }
}

當服務裝載於網際網路資訊服務 (IIS) 或 Windows Process Activation Service (WAS) 時,服務的基底位址是由裝載環境提供。 在自我裝載案例中,您必須自行指定基底位址。 這會使用 add 項目、<baseAddresses> 子項、<host> 子項、<service> 子項來完成,如下列範例組態所示。

<service
    name="Microsoft.ServiceModel.Samples.CalculatorService"
    behaviorConfiguration="CalculatorServiceBehavior">
  <host>
    <baseAddresses>
      <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
    </baseAddresses>
  </host>
  ...
</service>

當您執行範例時,作業要求和回應會顯示在服務與用戶端主控台視窗中。 在每個主控台視窗中按下 ENTER 鍵,即可關閉服務與用戶端。

若要安裝、建置及執行範例

  1. 確定您已執行 Windows Communication Foundation 範例的一次性安裝程序

  2. 若要建置方案的 C# 或 Visual Basic .NET 版本,請遵循 Building the Windows Communication Foundation Samples中的指示。

  3. 若要在單一或多部電腦組態中執行此範例,請遵循執行 Windows Communication Foundation 範例中的指示進行。

另請參閱