参考文档:http://docs.topshelf-project.com/en/latest/
github地址:https://github.com/Topshelf/Topshelf
Topshelf 是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主。
使用Topshelf可以非常方便的将一个C#控制台程序部署成为一个Windows Service,使用它可以很方便的构建跨平台服务寄主,而在调试时直接以控制台的形式运行即可,非常方便。
常规代码
var rc = HostFactory.Run(x => { x.Service<MyService>(s => { s.ConstructUsing(settings => new MyService(settings, path, ip, port)); s.WhenStarted(tc => tc.StartServer()); s.WhenStopped(tc => tc.StopServer()); }); x.RunAsLocalSystem(); x.EnableStartParameters(); x.SetDescription("我的Topshelf服务"); x.SetDisplayName("service_topshelf_demo"); x.SetServiceName("service_topshelf_demo"); x.WithStartParameter("config", a => path = a); x.WithStartParameter("ipaddress", a => ip = a); x.WithStartParameter("port", a => port = Convert.ToUInt16(a)); var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); Environment.ExitCode = exitCode;
VS中引用方式
打开NuGet 程序包管理界面 搜索 topshelf 然后安装;或者 在VS命令行窗体中键入指令 Install-Package Topshelf
安装、运行、停止和卸载服务
管理员方式运行命令行窗口(cmd.exe)
安装服务 XX服务.exe install
启动服务 XX服务.exe start
停止服务 XX服务.exe stop
卸载服务 XX服务.exe uninstall
Topshelf 设置项概要说明
1. 服务的启动模式
可以指定多种服务的启动模式,这些选项只在服务安装后有效。
HostFactory.Run(x =>{x.StartAutomatically();// 服务自动启动x.StartAutomaticallyDelayed();// 服务自动启动(延时启动) -- 需要 .NET 4.0 或以上版本x.StartManually();// 手动启动服务x.Disabled();// 服务禁用状态});
2. 指定服务运行的身份
HostFactory.Run(x =>{ x.RunAs("username","password");//使用指定用户名和密码运行服务,用户名中包含域:domain\username 或者 username@suffix.com//x.RunAsPrompt();//安装服务时,提示输入用户名和密码用于启动服务//x.RunAsNetworkService();//使用内置的 NETWORK_SERVICE 账户运行服务//x.RunAsLocalSystem();//使用本地系统账户运行//x.RunAsLocalService();//使用本地服务账户运行});
3. 自定义安装或卸载时执行的动作
这些操作允许在服务安装或卸载的过程中执行用户指定的方法。这里需要特别注意,一定是服务安装或卸载时有效!方法中可以使用服务的实例名称、服务名称等。
HostFactory.Run(x=>{ x.BeforeInstall(settings=>{ ... });//安装服务前执行x.AfterInstall(settings=>{ ... });//安装服务后执行x.BeforeUninstall(()=>{ ... });//卸载服务前执行x.AfterUninstall(()=>{ ... });//卸载服务后执行});
4. 指定依赖的服务
可以指定服务依赖项,以便在依赖服务启动之前不会启动服务。这是由 windows 服务控制管理器管理的,而不是由 Topshelf 本身管理的。
HostFactory.Run(x =>{x.DependsOn("SomeOtherService");});//对于知名的服务,有很多内置的扩展方法,包括:HostFactory.Run(x =>{x.DependsOnMsmq();// Microsoft Message Queueingx.DependsOnMsSql();// Microsoft SQL Serverx.DependsOnEventLog();// Windows Event Logx.DependsOnIis();// Internet Information Server});
5. 支持服务管理器暂停、继续、关闭等
HostFactory.Run(x =>{x.EnablePauseAndContinue();//允许服务控制管理器向服务传递暂停和继续命令x.EnableShutdown();//允许服务控制管理器快速关闭服务x.OnException(ex => {//此功能为服务运行时引发的异常提供回调。此回调不是处理程序,也不会影响 Topshelf 已经提供的默认异常处理程序//它旨在为触发外部操作如异常记录等});});
6. 服务恢复选项
HostFactory.Run(x =>{x.EnableServiceRecovery(r => {//恢复操作按指定的顺序执行,上一个操作运行后执行下一个操作//可以执行多少个操作是有限制的 (基于操作系统),通常是 2-3 个操作。r.RestartComputer(5,"message");r.RestartService(1);// 1分钟后重启服务//因为最多执行3个操作,最后一个将会执行后续所有的失败r.RunProgram(7,"ping google.com");// 运行程序,例如 notepad.exer.SetResetPeriod(1);// 将重置间隔设置为一天});});
Topshelf 扩展
目前已有许多依据Topshelf扩展的程序包,待研究。。。