Create a Windows service using Topshelf
Overview
Topshelf is another way to create a Windows service, a foreigner article create a. NET Windows service in 5 steps with Topshelf uses Topshelf to create a Windows service by using the 5-step detailed introduction. Topshelf is an open-source, cross-platform hosting service framework that supports Windows and mono and can build a convenient service host with just a few lines of code.
Reference installation
1, official website: http://topshelf-project.com/This has the detailed document and the download
2, topshelf code hosted in Http://github.com/topshelf/Topshelf/downloads, you can download to the latest code here.
3, a new project, only need to refer to Topshelf.dll, in order to display the log output, the proposal is also quoted Topshelf.log4net. Program installation Commands
- Install-package topshelf
- Install-package topshelf.log4net
Use
Official website documents to the example is very simple, direct use can run up, official website document address: http://docs.topshelf-project.com/en/latest/configuration/quickstart.html
public class towncrier{ReadOnly Timer _timer; Public Towncrier () {_timer = new timer (+) {AutoReset = true}; _timer. Elapsed + = (sender, EventArgs) = Console.WriteLine ("It is {0} and all are 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.construc Tusing (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}}
After the program runs, every second there is output, see the effect as follows:
Configuration Run
Yes, the entire program has been developed, then, just a simple configuration, that can be used when the service. Installation is convenient:
Installation: TopshelfDemo.exe Install start: TopshelfDemo.exe start uninstall: TopshelfDemo.exe Uninstall
After the installation is successful, we can see one more service in the service:
Extension description Topshelf Configuration simple configurations
Official documents, the parameters inside the hostfactory are described in detail: http://docs.topshelf-project.com/en/latest/configuration/config_api.html, Here are just a few simple explanations for common methods:
Let's change the program code above:
Hostfactory.run (x =//1 {x.service<towncrier> (s) = 2 {s.constructusing (name = new Towncrier ()); Configure a fully customized service that has no dependencies on topshelf. The usual way.
The start and stop methods for the service
s.whenstarted (TC = TC). Start ()); 4 s.whenstopped (TC = TC. Stop ()); 5}); X.runaslocalsystem (); The service runs using the Network_service built-in account. Identity, there are several ways, such as: X. RunAs ("username", "password"); X.runasprompt (); X.runasnetworkservice (); X.setdescription ("Description of the Sample topshelf Host service"); After the service is installed, the description of the service x.setdisplayname ("Stuff display name"); Display name X.setservicename ("Stuff Service name"); Service name});
After the reload installation is run:
Through above, I believe everyone is very clear setdescription, setdisplayname, setservicename difference. No longer elaborate.
Service Configuration Services Configurations
Topself services generally have two main modes of usage.
One, simple mode. Inherit the ServiceControl interface and implement the interface.
Instance:
Namespace topshelfdemo{public class Towncrier:servicecontrol {private Timer _timer = null; ReadOnly ILog _log = Logmanager.getlogger (typeof (Towncrier)); Public Towncrier () {_timer = new timer (+) {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 (A PpDomain.CurrentDomain.BaseDirectory + "Log4net.config"); Xmlconfigurator.configureandwatch (LOGCFG); Hostfactory.run (x = {x.service<towncrier> (); X.runaslocalsystem(); X.setdescription (Description of the "Sample topshelf Host Service"); X.setdisplayname ("Stuff display name"); X.setservicename ("Stuff Service name"); }); } }}
Second, the common mode.
Instance:
Namespace topshelfdemo{public class Towncrier {private Timer _timer = null; ReadOnly ILog _log = Logmanager.getlogger (typeof (Towncrier)); Public Towncrier () {_timer = new timer (+) {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 (A PpDomain.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 (Description of the "Sample topshelf Host Service"); X.setdisplayname ("Stuff display name"); X.setservicename ("Stuff Service name"); }); } }}
In both ways, the log4net is used, with the relevant configuration:
<?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 > <!--log path--<param name= "File" value= "D:\App_Data\servicelog\"/> <!--whether to append the log to the file--<param name= "Appendtofile" value= "true"/> <!--log retention days--<p Aram Name= "Maxsizerollbackups" value= "ten"/> <!--log file name is fixed---<param name= "Staticlogfilename" Value= "false"/> <!--log file name format is:2008-08-31.log--> <param name= "Datepattern" value= "Yyyy-mm-dd&qu OT;. log" " /> <!--logs by date scrolling-<param name= "Rollingstyle" value= "date"/> <layout type= "log4net. Layout.patternlayout "> <param name=" Conversionpattern "value="%d [%t] %-5p%c-%m%n%loggername "/> </layout> </appender> <!--console display logs--<appender n Ame= "Coloredconsoleappender" type= "log4net. Appender.coloredconsoleappender "> <mapping> <level value=" ERROR "/> <forecolor value= "Red, highintensity"/> </mapping> <mapping> <level value= "Info"/> <forec Olor value= "Green"/> </mapping> <layout type= "log4net. Layout.patternlayout "> <conversionpattern value="%n%date{hh:mm:ss,fff} [%-5level]%m "/> </layout& Gt <filter type= "log4net. Filter.levelrangefilter "> <param name=" levelmin "value=" Info "/> <param name=" Levelmax "value=" F Atal "/> </filter> </appender> <root> <!--(high) OFF > FATAL > ERROR > WARN > INFO > DEBUG > All (Low)--<level value= "All"/> <appender-ref ref= "ColoredconsolEappender "/> <appender-ref ref=" Rollinglogfileappender "/> </root> </log4net></configurati On>
It is recommended to use the second common pattern.
Source code Download: http://download.csdn.net/detail/jys1216/8860119
Next, will introduce: Topself and quartz.net combination use, combine to use, really is a very perfect background job debugging service.
Topshelf Creating a Windows service