在windows服務中寄宿wcf服務,需要繼承ServiceBase,此外,還須要繼承Installer以安裝服務.以下為具體實作步驟:
1.建立檔案winservice.cs,輸入代碼
namespace windowswcfservice
{
using System.ServiceProcess;
using System.ServiceModel;
using System.Configuration.Install;
using System.Configuration;
using System.ComponentModel;
[ServiceContract(Namespace="http://mysample")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
double Subtract(double n1, double n2);
double Multiply(double n1, double n2);
double Divide(double n1, double n2);
}
public class CalculatorService : ICalculator
public double Add(double n1, double n2)
{
return n1 + n2;
}
public double Subtract(double n1, double n2)
return n1 - n2;
public double Multiply(double n1, double n2)
return n1 * n2;
public double Divide(double n1, double n2)
return n1 / n2;
[RunInstaller(true)]
public class ProjectInstaller : Installer
private ServiceProcessInstaller process;
private ServiceInstaller service;
public ProjectInstaller()
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "WCFWindowsServiceSample";
Installers.Add(process);
Installers.Add(service);
public class WindowsCalculatorService : ServiceBase
public ServiceHost serviceHost = null;
public static void Main()
ServiceBase.Run(new WindowsCalculatorService());
protected override void OnStart(string[] args)
if (serviceHost != null)
{
serviceHost.Close();
}
try
serviceHost = new ServiceHost(typeof(CalculatorService));
serviceHost.Open();
catch(System.Exception err)
System.Diagnostics.EventLog.WriteEntry("Application", err.Message);
protected override void OnStop()
serviceHost = null;
}
2.用csc編譯檔案winservice.cs
csc /t:exe winservice.cs /r:"C:/WINDOWS/Microsoft.NET/Framework/v3.0/Windows Communication Foundation/System.ServiceModel.dll" /r:C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/System.ServiceProcess.dll /r:System.Configuration.Install.dll
3.建立winservice.exe.config,内容如下:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="windowswcfservice.CalculatorService" behaviorConfiguration="Metadata" >
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/service"/>
</baseAddresses>
</host>
<endpoint address="*" binding="wsHttpBinding" contract="windowswcfservice.ICalculator" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Metadata">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
4.利用工具C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/installutil.exe安裝windows 服務.
installutil.exe winservice.exe
5.啟動服務:net start WCFWindowsServiceSample
如果服務不能啟動,可檢視事件日志以定位錯誤.
6.通路wcf服務:http://localhost:8000/service
7.停止wcf服務:net stop WCFWindowsServiceSample
8.解除安裝windows服務:installutil.exe /u winservice.exe