WindowsService 示例演示了一个 Windows Communication Foundation(WCF)服务,它托管在一个托管的 Windows 服务中。 Windows 服务使用 控制面板 中的服务小程序进行控制,并且可以配置为在系统重新启动后自动启动。 该示例由客户端程序和 Windows 服务程序组成。 该服务作为 .exe 程序实现,并包含其自己的托管代码。 在其他托管环境中,如 Windows 进程激活服务(WAS)或 Internet Information Services (IIS),无需编写托管代码。
注释
本示例的设置过程和生成说明位于本主题末尾。
生成此服务后,必须使用 Installutil.exe 实用工具安装它,就像任何其他 Windows 服务一样。 如果要对此服务进行更改,必须首先使用 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()中,通过调用Close(TimeSpan)对象的ServiceHost方法,关闭ServiceHost。 主机的基址是使用 <add> 元素配置的,该元素是 <baseAddresses> 的子元素,后者又是 <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 示例中的说明进行操作。