Fork me on GitHub

Topshelf 支持Mono 扩展Topshelf.Linux

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

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

image

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来完成这些工作。
posted @ 2014-05-25 10:15  张善友  阅读(3603)  评论(3编辑  收藏  举报