使用Topshelf建立Windows 服務
Winndows Service 是一種可隨 Windows 作業系統啟動而啟動的,在後台啟動並執行,通常不和使用者產生互動的程式。它無法通過雙擊來運行,類似於 Unix 守護進程(daemon processes),當使用者登出時它也不會停止。
Windows 服務由三部分組成:
- 一個服務可執行檔;
- 一個服務控製程序(SCP);
- 服務控制管理員(SCM),負責在 HKLM"SYSTEM"CurrentControlSet"Services 下建立服務索引值。使用者可通過 SCP 控制服務的啟動、停止、暫停等,SCP 會通過 SCM 調用服務程式
開發一個Windows服務通常也比較簡單,在開發的時候我們期望以命令列方式運行,想對Windows服務有更多的控制,就有一個Windows服務架構TopShelf 可以滿足,使用這個架構要求你使用一個IoC容器,在架構中使用的是common service locator 介面,可以根據你的喜好去選擇你自己中意的IoC容器。
TopShelf的基本介紹可以參看Dru Sellers 的介紹性文章 TopShelf。下面的代碼就是建立了一個Windows服務:
using System;
using System.Collections.Generic;
using System.IO;
using System.Timers;
using log4net.Config;
using Microsoft.Practices.ServiceLocation;
using StructureMap;
using Topshelf;
using Topshelf.Configuration;
internal class Program
{
static void Main(string[] args)
{
XmlConfigurator.ConfigureAndWatch(new FileInfo(".\\log4net.config"));
IRunConfiguration cfg = RunnerConfigurator.New(x =>
{
x.AfterStoppingTheHost(h => { Console.WriteLine("AfterStop called invoked, services are stopping"); });
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("Stuff");
x.SetServiceName("stuff");
x.ConfigureServiceInIsolation<TownCrier>("tc", s =>
{
s.CreateServiceLocator(()=>
{
ObjectFactory.Initialize(i =>
{
i.ForConcreteType<TownCrier>().Configure.WithName("tc");
});
return new StructureMapServiceLocator();
});
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
});
Runner.Host(cfg, args);
}
}
這裡我們使用了StructureMap 作為IoC容器,建立了一個StructureMapServiceLocator來掩藏StructureMap,建立的Windows服務的名稱是stuff,可以吊相應的方法啟動,停止服務。通過直接運行.exe檔案在控制台中運行或者調試服務了。
通過命令運行,安裝卸載Windows服務
Stuff.exe #控制台方式運行
Stuff.exe /install #安裝Windows服務
Stuff.exe /uninstall #卸載Windows服務
預設情況下,Windows服務只能運行一個執行個體,如果我們想運行多個執行個體怎麼辦,可以在Topshelf的命令列參數中增加–instance <instance name>來指定執行個體的名稱,也可以通過運行時讀取設定檔來達到目的,我更喜歡使用後一種方式設定,在應用程式的設定檔上增加個配置WindowsServiceInstanceName:
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
configuration
>
<
appSettings
file
=
"applicationSettings.config"
>
<
add
key
=
"WindowsServiceInstanceName"
value
=
"Stuff"
/>
</
appSettings
>
</
configuration
>
然後改造一下上述代碼
static void Main(string[] args)
{
var instanceName = ConfigurationManager.AppSettings["WindowsServiceInstanceName"];
XmlConfigurator.ConfigureAndWatch(new FileInfo(".\\log4net.config"));
IRunConfiguration cfg = RunnerConfigurator.New(x =>
{
x.AfterStoppingTheHost(h => { Console.WriteLine("AfterStop called invoked, services are stopping"); });
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName(instanceName );
x.SetServiceName(instanceName );
……
這樣我們就可以達到在同台機器上安裝多個Windows 服務執行個體,推薦大家使用這個Windows服務架構TopShelf ,可以簡化很多工作和增加靈活性