最近在看关于WCF的东西,动手写了个简单的例子,一切都很顺利,但我想把wcf寄宿到windows服务时耗费了时间。因不常做这类把应用程序寄宿到服务中,特此记录下。
- 首先保证要寄宿的wcf服务可以正常运行
- 在解决方案中右键->添加 一个windows服务,我这里取名为WcfServices,默认有一个Service1.cs的文件,里面有两个重写的方法,在OnStart中加入启动服务的代码,如下图
- 在Services1的设计页面,右键->添加安装程序,在WcfServices的目录下会多出一个ProjectInstaller.cs文件,可在这个文件的设计页面,设置serviceInstaller1和serviceProcessInstaller1的属性,当让也可以在代码中设置。
- 将wcf所需的配置加到app.config中
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<services>
<service behaviorConfiguration="Calculator" name="Services.Calculator">
<host>
<baseAddresses>
<add baseAddress="http://127.0.0.1:8888/Services/"/>
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract="Contracts.ICalculator" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Calculator">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
- windows 服务在vs中不能直接F5运行,我们编译后,用命令将其加入到windows服务中。
- 用管理员身份运行cmd,转到以下目录
- 运行 installUtil E:\WcfService\WcfServices\bin\Debug\WcfServices.exe (这是要寄宿的服务路径),这样就可以在windows服务中看到加进去的服务了
- 直接启动就ok了
- 测试一下,在ie下访问http://127.0.0.1:8888/Services/(这个是wcf服务地址),如果看到下面的页面就表示服务启动成功了
PS:如要卸载此服务,执行installUtil -u E:\WcfService\WcfServices\bin\Debug\WcfServices.exe 即可,执行完成后若要再安装,需先关闭服务对话框,不然会报该服务被标记为删除之类的错误