Topshelf是创建Windows服务的另一种方法。Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主。
一、引用
新建一个项目,只需要引用Topshelf.dll 即可,为了日志输出显示,建议也同时引用Topshelf.Log4Net。程序安装命令:
- Install-Package Topshelf
- Install-Package Topshelf.Log4Net
二、使用
1 public class TownCrier 2 { 3 readonly Timer _timer; 4 public TownCrier() 5 { 6 _timer = new Timer(1000) {AutoReset = true}; 7 _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); 8 } 9 public void Start() { _timer.Start(); } 10 public void Stop() { _timer.Stop(); } 11 } 12 13 public class Program 14 { 15 public static void Main() 16 { 17 var rc = HostFactory.Run(x => //1 18 { 19 x.Service<TownCrier>(s => //2 20 { 21 s.ConstructUsing(name=> new TownCrier()); //配置一个完全定制的服务,对Topshelf没有依赖关系。常用的方式。 22 s.WhenStarted(tc => tc.Start()); 23 s.WhenStopped(tc => tc.Stop()); 24 }); 25 x.RunAsLocalSystem(); //服务使用NETWORK_SERVICE内置帐户运行。身份标识,有好几种方式,如: 26 //x.RunAs("username", "password"); x.RunAsPrompt(); x.RunAsNetworkService(); 等 27 x.SetDescription("Sample Topshelf Host"); //安装服务后,服务的描述 28 x.SetDisplayName("Stuff"); //显示名称 29 x.SetServiceName("Stuff"); //服务名称 30 }); 31 32 var exitCode = (int) Convert.ChangeType(rc, rc.GetTypeCode()); 33 Environment.ExitCode = exitCode; 34 } 35 }
三、运行
程序跑起来后,每隔一秒钟有输出,看到的效果如下:
四、配置成服务运行
只需要简单配置一下,即可以当服务来使用了。安装很方便:
安装:TopshelfDemo.exe install
启动:TopshelfDemo.exe start
卸载:TopshelfDemo.exe uninstall

安装成功后,接下来,我们就可以看到服务里多了一个服务:

五、服务使用模式
Topself的服务一般有主要有两种使用模式。
1、简单模式。继承ServiceControl接口,实现该接口即可。
HostFactory.New(x => { x.Service<MyService>(); }); // Service implements the ServiceControl methods directly and has a default constructor class MyService : ServiceControl {}
2、自定义模式。配置成完全自定义的服务,不依赖Topshelf.
HostFactory.New(x => { x.Service<MyService>(sc => { sc.ConstructUsing(() => new MyService()); // the start and stop methods for the service sc.WhenStarted(s => s.Start()); sc.WhenStopped(s => s.Stop()); // optional pause/continue methods if used sc.WhenPaused(s => s.Pause()); sc.WhenContinued(s => s.Continue()); // optional, when shutdown is supported sc.WhenShutdown(s => s.Shutdown()); }); });
深入学习网址:http://docs.topshelf-project.com/en/latest/configuration/quickstart.html