
WCF寄宿到Windows Service[1]
2014-06-14
WCF寄宿到Windows Service
在前面创建一个简单的WCF程序,我们把WCF的服务寄宿到了Host这个控制台项目中了。下面将介绍如何把WCF的服务寄宿到Windows服务中(源代码):
1. 删除原来Host控制台项目,然后在solution上右键,新建一个WindowService项目。如下图:
2.对WcfServices.HostingWindowsSerice项目添加对Contracts项目、Service项目和System.ServiceModel的引用。
3.将WcfServices.HostingWindowsSerice项目中的Class1.cs文件重命名为CalculatorHost.cs,然后打开这个文件,里面代码如下:
using System.ServiceProcess;
using System.ServiceModel;
using WcfServices.Services; namespace WcfServices.HostingWindowsService
{
public partial class CalculatorHost : ServiceBase
{
private ServiceHost _host; public ServiceHost Host
{
get { return _host; }
set { _host = value; }
} public CalculatorHost()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
Host = new ServiceHost(typeof(CalculatorService));
Host.Open();
} protected override void OnStop()
{
if (Host != null)
{
Host.Close();
Host = null;
} }
}
}
4.CalculatorHost.cs[Design]的界面上右键,选择添加安装器(Add Installer)。这时,项目里会自动生成一个ProjectInstaller.cs文件。
5.打开ProjectInstaller.cs[Design]的设计界面,将会出现下图:
6.选中serviceInstaller1,打开它的属性视图(Ctrl W,P),修改属性。如下图所示:
7.接着选中serviceProcessInstaller1,打开它的属性视图,修改属性。如下图:(这里服务账号也可以是其他的。)
8.接下来我们看看这个项目里的program.cs文件。代码如下:
using System.ServiceProcess; namespace WcfServices.HostingWindowsService
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new CalculatorHost()
};
ServiceBase.Run(ServicesToRun);
}
}
}
9.这些都做好了之后,在WcfServices.HostingWindowsSerice项目中添加服务端的配置文件。这个在上一节中也写过,代码如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CaclulaterBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="CaclulaterBehavior" name="WcfServices.Services.CalculatorService">
<endpoint address="http://localhost:8080/calculatorservice" binding="basicHttpBinding"
bindingConfiguration="" contract="WcfServices.Contracts.ICalculator" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/calculatorservice" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
10.Build项目WcfServices.HostingWindowsSerice,查看生成的文件如下:
将整个debug文件夹中文件拷出来,放到另外一个目录下。比如D:\WCF\CalculatorService中。后面我们注册的windows服务将从这个目录下找exe文件。
11.下面就是要注册了。我们用InstallUtil.exe来注册(当然你也可以用sc)。打开InstallUtil.exe在我的电脑的目录是:C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319。你可以从命令行进如这个目录,然后执行InstallUtil命令。也可以在所有程序中找到visual studio Tools,里面的visual studio command prompt命令行工具。执行安装的命令是InstallUtil D:\WCF\CalculatorService\WcfServices.HostingWindowsSerice.exe
12.成功后,你就可以在控制面板->管理工具->服务中找到它了,如下图:
参考:
[1] WCF注册Windows Service http://www.cnblogs.com/judastree/archive/2012/08/29/2662184.html