Welcome

首页 / 软件开发 / .NET编程技术 / Topshelf如何支持Mono扩展Topshelf.Linux

Topshelf如何支持Mono扩展Topshelf.Linux2015-12-03 cnblogs 张善友使用Topshelf 5步创建Windows 服务 这篇文章大家可以了解到使用Topshelf可以很好的支持Windows服务的开发,但是它和Mono不兼容,Github上有一个扩展https://github.com/pruiz/Topshelf.Linux 可以很好兼容Linux/Mono,本文介绍使用方法:

1、在项目中添加Topshelf.Linux, 通过Nuget 很方便的添加引用:

2、在代码中加入下面一行代码UseLinuxIfAvailable() :

class Program{static ILog _log = LogManager.GetLogger(typeof(Program));static void Main(string[] args){System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config"));var host = HostFactory.New(x =>{x.Service<SampleService>(s =>{s.ConstructUsing(() => new SampleService());s.WhenStarted(v => v.Start());s.WhenStopped(v => v.Stop());});x.UseLinuxIfAvailable(); x.RunAsLocalSystem();x.UseLog4Net();x.SetDescription("SampleService Description");x.SetDisplayName("SampleService");x.SetServiceName("SampleService");});host.Run();}
这样你的基于Topshelf Windows服务就完成了兼容Mono的改造工作。但是要注意的是在Mono下支持命令行运行,不能使用Topshelf的命令行Start,Stop控制服务等,这对于Linux环境来说足够了,可以通过rc-scripts来完成这些工作。