問題:
在前面建立的WCF的HelloWorld程式,我們把WCF的服務寄宿到了Host這個控制台項目中了。現在你想將WCF的服務寄宿到Windows服務中。
解決過程:
- 刪除原來Host控制台項目,然後在solution上右鍵,建立一個WindowService項目。如:
- 對MyFirstWindowsService項目添加對Contracts項目、Service項目和System.ServiceModel的引用。
- 將MyFristWindowsService項目中的Class1.cs檔案重新命名為HelloHost.cs,然後開啟這個檔案,裡面代碼如下:
- HelloHost.cs
namespace MyFirstWindowsService{ partial class HelloHost : ServiceBase { private ServiceHost _host; public ServiceHost Host { get { return _host; } set { _host = value; } } public HelloHost() { InitializeComponent(); } protected override void OnStart(string[] args) { // TODO: Add code here to start your service. Host = new ServiceHost(typeof(HelloWorld)); Host.Open(); } protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. if (Host != null) { Host.Close(); Host = null; } } }} g
- HelloHost.cs[Design]的介面上右鍵,選擇添加安裝器(Add Installer)。這時,項目裡會自動產生一個ProjectInstaller.cs檔案。
- 開啟ProjectInstaller.cs[Design]的設計介面,將會出現:
- 選中serviceInstaller1,開啟它的屬性視圖(Ctrl W,P),修改屬性。如所示:
- 接著選中serviceProcessInstaller1,開啟它的屬性視圖,修改屬性。如:(這裡服務帳號也可以是其他的。)
- 接下來我們看看這個項目裡的program.cs檔案。代碼如下:Program.cs
namespace MyFirstWindowsService{ static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new HelloHost(), }; ServiceBase.Run(ServicesToRun); } }}
- 這些都做好了之後,在MyFirstWindowsService項目中添加服務端的設定檔。這個在上一節中也寫過,代碼如下:App.config
<?xml version="1.0"?><configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="HelloWorldBehavior"> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="HelloWorldBehavior" name="Services.HelloWorld"> <endpoint address="Hello" binding="basicHttpBinding" name="Hello" contract="Contracts.IHello" listenUriMode="Explicit" /> <endpoint address="mexHello" binding="mexHttpBinding" bindingConfiguration="" name="mexHello" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://localhost:8080/Service" /> </baseAddresses> </host> </service> </services> </system.serviceModel><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
- 現在我們的solution的目錄是這個樣子的:F6,Build。確保build success。
- 開啟MyFirstWindowsService項目的bin/debug檔案。在項目上右鍵,open folder in Windows explorer。debug檔案夾中有如下檔案:
- 將整個debug檔案夾中檔案拷出來,放到另外一個目錄下。我這兒是放在C:\FirstService中。後面我們註冊的windows服務將從這個目錄下找exe檔案。
- 下面就是要註冊了。我們用InstallUtil.exe來註冊(當然你也可以用sc)。開啟InstallUtil.exe在我的電腦的目錄是:C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319。你可以從命令列進如這個目錄,然後執行InstallUtil命令。也可以在所有程式中找到visual studio Tools,裡面的visual studio command prompt命令列工具。執行安裝的命令是InstallUtil C:\FirstService\MyFirstWindowsService.exe
- 成功後,你就可以在控制台-》管理工具-》服務中找到它了。