WindowsService 範例示範裝載在受控 Windows 服務中的 Windows Communication Foundation (WCF) 服務。 Windows 服務是使用 [控制面板 ] 中的 [服務] 小程式來控制,並可設定為在系統重新啟動後自動啟動。 此範例包含用戶端程式和 Windows 服務程式。 服務會實作為 .exe 程式,並包含它自己的主控程序代碼。 在其他裝載環境中,例如 Windows Process Activation Services (WAS) 或 Internet Information Services (IIS),您不需要撰寫裝載程式代碼。
備註
此範例的設定程式和建置指示位於本主題結尾。
建置此服務之後,必須與任何其他 Windows 服務一樣,使用 Installutil.exe 公用程式進行安裝。 如果您要對服務進行變更,您必須先使用 installutil /u
卸載服務。 此範例中包含的 Setup.bat 和 Cleanup.bat 檔案是安裝及啟動 Windows 服務的命令,以及關閉和卸載 Windows 服務。 WCF 服務只能在 Windows 服務執行時回應用戶端。 如果您使用 控制面板 的服務小程式來停止 Windows 服務,並執行客戶端, EndpointNotFoundException 當客戶端嘗試存取服務時,就會發生例外狀況。 如果您重新啟動 Windows 服務並重新執行用戶端,則通訊會成功。
服務程式代碼包含安裝程式類別、實作 ICalculator 合約的 WCF 服務實作類別,以及做為運行時間主機的 Windows 服務類別。 繼承自 Installer的安裝程式類別可讓程式由 Installutil.exe 工具安裝為NT服務。 服務實作類別 WcfCalculatorService
是實作基本服務合約的 WCF 服務。 此 WCF 服務裝載於名為 WindowsCalculatorService
的 Windows 服務類別內。 為了符合 Windows 服務資格,類別會繼承自 ServiceBase 並實作 OnStart(String[]) 和 OnStop() 方法。 在 OnStart(String[]) 中,會為 ServiceHost 型別建立一個 WcfCalculatorService
對象並開啟。 在 OnStop() 中,ServiceHost 會藉由呼叫 Close(TimeSpan) 物件的 ServiceHost 方法來關閉。 主機的基位址是使用 <add> 元素來設定,這個元素是 <baseAddresses> 的子元素,而 <baseAddresses> 則是 <host> 元素的子元素,<host> 又是 service 元素的子元素。
定義的端點會使用基本位址和 <wsHttpBinding>。 下列範例顯示基位址的組態,以及公開 CalculatorService 的端點。
<services>
<service name="Microsoft.ServiceModel.Samples.WcfCalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
</baseAddresses>
</host>
<!-- This endpoint is exposed at the base address provided by host: http://localhost:8000/ServiceModelSamples/service. -->
<endpoint address=""
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
...
</service>
</services>
當您執行範例時,作業要求和回應會顯示在服務和用戶端控制台視窗中。 在每個主控台視窗中按 ENTER 鍵,關閉服務和用戶端。
要設定、建置和執行範例,請執行以下步驟:
請確定您已針對 Windows Communication Foundation 範例 執行One-Time 安裝程式。
若要建置解決方案的 C# 或 Visual Basic .NET 版本,請遵循建置 Windows Communication Foundation 範例 中中的指示。
建置解決方案之後,請從以系統管理員身份開啟的 Visual Studio 命令提示字元執行 Setup.bat,從而使用 Installutil.exe 工具安裝 Windows 服務。 服務應該會出現在 [服務] 中。
若要在單一或跨計算機組態中執行範例,請遵循 執行 Windows Communication Foundation 範例中的指示。