Winndows Service 是一種可隨 Windows 操做系統啓動而啓動的,在後臺運行的,一般不和用戶產生交互的程序。它沒法經過雙擊來運行,相似於 Unix 守護進程(daemon processes),當用戶註銷時它也不會中止。app
Windows 服務由三部分組成:框架
開發一個Windows服務一般也比較簡單,在開發的時候咱們指望以命令行方式運行,想對Windows服務有更多的控制,就有一個Windows服務框架TopShelf 能夠知足,使用這個框架要求你使用一個IoC容器,在框架中使用的是common service locator 接口,能夠根據你的喜愛去選擇你本身中意的IoC容器。google
TopShelf的基本介紹能夠參看Dru Sellers 的介紹性文章 TopShelf。下面的代碼就是建立了一個Windows服務:spa
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");
});code
return new StructureMapServiceLocator();
});
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
}); xml
x.RunAsLocalSystem();blog
});
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 ,能夠簡化不少工做和增長靈活性