Topshelf是建立Windows服務的另外一種方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf經過5個步驟詳細的介紹使用使用Topshelf建立Windows 服務。Topshelf是一個開源的跨平臺的宿主服務框架,支持Windows和Mono,只須要幾行代碼就能夠構建一個很方便使用的服務宿主。html
一、官網:http://topshelf-project.com/ 這裏面有詳細的文檔及下載git
二、Topshelf的代碼託管在 http://github.com/topshelf/Topshelf/downloads ,能夠在這裏下載到最新的代碼。github
三、新建一個項目,只須要引用Topshelf.dll 便可,爲了日誌輸出顯示,建議也同時引用Topshelf.Log4Net。程序安裝命令windows
官網文檔給過來的例子很是簡單,直接使用便可以跑起來,官網文檔地址:http://docs.topshelf-project.com/en/latest/configuration/quickstart.htmlapi
public class TownCrier { readonly Timer _timer; public TownCrier() { _timer = new Timer(1000) {AutoReset = true}; _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); } public void Start() { _timer.Start(); } public void Stop() { _timer.Stop(); } } public class Program { public static void Main() { HostFactory.Run(x => //1 { x.Service<TownCrier>(s => //2 { s.ConstructUsing(name=> new TownCrier()); //3 s.WhenStarted(tc => tc.Start()); //4 s.WhenStopped(tc => tc.Stop()); //5 }); x.RunAsLocalSystem(); //6 x.SetDescription("Sample Topshelf Host"); //7 x.SetDisplayName("Stuff"); //8 x.SetServiceName("Stuff"); //9 }); //10 } }
程序跑起來後,每隔一秒鐘有輸出,看到的效果以下:app
沒錯,整個程序已經開發完了,接下來,只須要簡單配置一下,便可以當服務來使用了。安裝很方便:框架
安裝成功後,接下來,咱們就能夠看到服務裏多了一個服務:ui
官方文檔,對HostFactory 裏面的參數作了詳細的說明:http://docs.topshelf-project.com/en/latest/configuration/config_api.html ,下面只對一些經常使用的方法進行簡單的解釋:spa
咱們將上面的程序代碼改一下:.net
HostFactory.Run(x => //1 { x.Service<TownCrier>(s => //2 { s.ConstructUsing(name => new TownCrier()); //配置一個徹底定製的服務,對Topshelf沒有依賴關係。經常使用的方式。
//the start and stop methods for the service
s.WhenStarted(tc => tc.Start()); //4 s.WhenStopped(tc => tc.Stop()); //5 }); x.RunAsLocalSystem(); // 服務使用NETWORK_SERVICE內置賬戶運行。身份標識,有好幾種方式,如:x.RunAs("username", "password"); x.RunAsPrompt(); x.RunAsNetworkService(); 等 x.SetDescription("Sample Topshelf Host服務的描述"); //安裝服務後,服務的描述 x.SetDisplayName("Stuff顯示名稱"); //顯示名稱 x.SetServiceName("Stuff服務名稱"); //服務名稱 });
重裝安裝運行後:
經過上面,相信你們都很清楚 SetDescription、SetDisplayName、SetServiceName區別。再也不細說。
Topself的服務通常有主要有兩種使用模式。
實例:
namespace TopshelfDemo { public class TownCrier : ServiceControl { private Timer _timer = null; readonly ILog _log = LogManager.GetLogger(typeof(TownCrier)); public TownCrier() { _timer = new Timer(1000) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => _log.Info(DateTime.Now); } public bool Start(HostControl hostControl) { _log.Info("TopshelfDemo is Started"); _timer.Start(); return true; } public bool Stop(HostControl hostControl) { throw new NotImplementedException(); } } class Program { public static void Main(string[] args) { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg); HostFactory.Run(x => { x.Service<TownCrier>(); x.RunAsLocalSystem(); x.SetDescription("Sample Topshelf Host服務的描述"); x.SetDisplayName("Stuff顯示名稱"); x.SetServiceName("Stuff服務名稱"); }); } } }
實例:
namespace TopshelfDemo { public class TownCrier { private Timer _timer = null; readonly ILog _log = LogManager.GetLogger( typeof(TownCrier)); public TownCrier() { _timer = new Timer(1000) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => _log.Info(DateTime.Now); } public void Start(){ _timer.Start();} public void Stop() { _timer.Stop(); } } class Program { public static void Main(string[] args) { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg); HostFactory.Run(x => { x.Service<TownCrier>(s => { s.ConstructUsing(name => new TownCrier()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("Sample Topshelf Host服務的描述"); x.SetDisplayName("Stuff顯示名稱"); x.SetServiceName("Stuff服務名稱"); }); } } }
兩種方式,都使用了Log4Net,相關配置:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日誌路徑--> <param name= "File" value= "D:\App_Data\servicelog\"/> <!--是不是向文件中追加日誌--> <param name= "AppendToFile" value= "true"/> <!--log保留天數--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日誌文件名是不是固定不變的--> <param name= "StaticLogFileName" value= "false"/> <!--日誌文件名格式爲:2008-08-31.log--> <param name= "DatePattern" value= "yyyy-MM-dd".log""/> <!--日誌根據日期滾動--> <param name= "RollingStyle" value= "Date"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <!-- 控制檯前臺顯示日誌 --> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="Info" /> <foreColor value="Green" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="Info" /> <param name="LevelMax" value="Fatal" /> </filter> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="ColoredConsoleAppender"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>
推薦使用第二種經常使用模式。