【轉】使用Topshelf建立Windows服務

來源:互聯網
上載者:User

標籤:date   pat   rgs   back   技術分享   tle   技術   介面   class   

轉自:http://www.cnblogs.com/jys509/p/4614975.html

 

概述

Topshelf是建立Windows服務的另一種方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf通過5個步驟詳細的介紹使用使用Topshelf建立Windows 服務。Topshelf是一個開源的跨平台的宿主服務架構,支援Windows和Mono,只需要幾行代碼就可以構建一個很方便使用的服務宿主。

引用安裝

1、官網:http://topshelf-project.com/  這裡面有詳細的文檔及下載

2、Topshelf的代碼託管在 http://github.com/topshelf/Topshelf/downloads   ,可以在這裡下載到最新的代碼。

3、建立一個項目,只需要引用Topshelf.dll 即可,為了日誌輸出顯示,建議也同時引用Topshelf.Log4Net。程式安裝命令

  • Install-Package Topshelf
  • Install-Package Topshelf.Log4Net
使用

官網文檔給過來的例子非常簡單,直接使用即可以跑起來,官網文檔地址:http://docs.topshelf-project.com/en/latest/configuration/quickstart.html

public class TownCrier{    readonly Timer _timer;    public TownCrier()    {        _timer = new Timer(1000) {AutoReset = true};        _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is 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.ConstructUsing(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    }}

程式跑起來後,每隔一秒鐘有輸出,看到的效果如下:

配置運行

沒錯,整個程式已經開發完了,接下來,只需要簡單配置一下,即可以當服務來使用了。安裝很方便:

安裝:TopshelfDemo.exe install啟動:TopshelfDemo.exe start卸載:TopshelfDemo.exe uninstall

安裝成功後,接下來,我們就可以看到服務裡多了一個服務:

擴充說明Topshelf Configuration 簡單配置

官方文檔,對HostFactory 裡面的參數做了詳細的說明:http://docs.topshelf-project.com/en/latest/configuration/config_api.html ,下面只對一些常用的方法進行簡單的解釋:

我們將上面的程式碼改一下:

            HostFactory.Run(x =>                                 //1            {                x.Service<TownCrier>(s =>                        //2                {                    s.ConstructUsing(name => new TownCrier());     //配置一個完全定製的服務,對Topshelf沒有依賴關係。常用的方式。
            //the start and stop methods for the service
                    s.WhenStarted(tc => tc.Start()); //4 s.WhenStopped(tc => tc.Stop()); //5 }); x.RunAsLocalSystem(); // 服務使用NETWORK_SERVICE內建帳戶運行。身份標識,有好幾種方式,如:x.RunAs("username", "password"); x.RunAsPrompt(); x.RunAsNetworkService(); 等 x.SetDescription("Sample Topshelf Host服務的描述"); //安裝服務後,服務的描述 x.SetDisplayName("Stuff顯示名稱"); //顯示名稱 x.SetServiceName("Stuff服務名稱"); //服務名稱 });

重裝安裝運行後:

 通過上面,相信大家都很清楚 SetDescription、SetDisplayName、SetServiceName區別。不再細說。

Service Configuration 服務配置

Topself的服務一般有主要有兩種使用模式。

一、簡單模式。繼承ServiceControl介面,實現該介面即可。

執行個體:

namespace TopshelfDemo{    public class TownCrier : ServiceControl    {        private Timer _timer = null;        readonly ILog _log = LogManager.GetLogger(typeof(TownCrier));        public TownCrier()        {            _timer = new Timer(1000) { 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(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");            XmlConfigurator.ConfigureAndWatch(logCfg);            HostFactory.Run(x =>            {                x.Service<TownCrier>();                x.RunAsLocalSystem();                x.SetDescription("Sample Topshelf Host服務的描述");                x.SetDisplayName("Stuff顯示名稱");                x.SetServiceName("Stuff服務名稱");            });        }    }}
二、常用模式。

執行個體:

namespace TopshelfDemo{    public class TownCrier    {        private Timer _timer = null;        readonly ILog _log = LogManager.GetLogger(                                         typeof(TownCrier));        public TownCrier()        {            _timer = new Timer(1000) { 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(AppDomain.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("Sample Topshelf Host服務的描述");                x.SetDisplayName("Stuff顯示名稱");                x.SetServiceName("Stuff服務名稱");            });        }    }}

兩種方式,都使用了Log4Net,相關配置:

<?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">      <!--日誌路徑-->      <param name= "File" value= "D:\App_Data\servicelog\"/>      <!--是否是向檔案中追加日誌-->      <param name= "AppendToFile" value= "true"/>      <!--log保留天數-->      <param name= "MaxSizeRollBackups" value= "10"/>      <!--記錄檔名是否是固定不變的-->      <param name= "StaticLogFileName" value= "false"/>      <!--記錄檔名格式為:2008-08-31.log-->      <param name= "DatePattern" value= "yyyy-MM-dd&quot;.log&quot;"/>      <!--日誌根據日期滾動-->      <param name= "RollingStyle" value= "Date"/>      <layout type="log4net.Layout.PatternLayout">        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" />      </layout>    </appender>    <!-- 控制台前台顯示日誌 -->    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">      <mapping>        <level value="ERROR" />        <foreColor value="Red, HighIntensity" />      </mapping>      <mapping>        <level value="Info" />        <foreColor value="Green" />      </mapping>      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />      </layout>      <filter type="log4net.Filter.LevelRangeFilter">        <param name="LevelMin" value="Info" />        <param name="LevelMax" value="Fatal" />      </filter>    </appender>    <root>      <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->      <level value="all" />      <appender-ref ref="ColoredConsoleAppender"/>      <appender-ref ref="RollingLogFileAppender"/>    </root>  </log4net></configuration>

 推薦使用第二種常用模式。

原始碼下載:http://download.csdn.net/detail/jys1216/8860119

【轉】使用Topshelf建立Windows服務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.