Topshelf Windows Service

使用 Topshelf 簡化 Windows Service 開發

陳志澤 2019/12/09 11:06:11
25825

為什麼使用 Topshelf

使用傳統開發 Windows Service 方式時,必定會面臨到如何在開發時期進行偵錯的問題,當然利用一些小技巧是可以達成 (ex. 參考 如何對 Windows Service 進行除錯 文章),但到底還是要手動切換;透過 Topshelf 這個套件可以讓開發者直接使用 Console 方式進行開發,編譯出來就是一隻 console 程式且可以獨自運行,又可以透過命令列指令將這個 console 執行檔安裝成為 Windows Service 服務,達到易於開發、偵錯及靈活使用的優點,以下介紹。

 

 

開發實作說明

首先建立一個 Console 專案

 

透過 Nuget 下載 Topshelf 套件 (目前版本為 4.2.1)

 

接著簡單建立一個 MainService 物件,用來處理此服務主要作業邏輯,以及開始與結束作業邏輯;所以一個最精簡的 Timer 重複性作業結構如下所示,

class MainService
{
    private Timer _timer;

    public MainService()
    {
        _timer = new Timer(1000) { AutoReset = true };
        _timer.Elapsed += new ElapsedEventHandler(this.MainTask);
    }

    private void MainTask(object sender, ElapsedEventArgs args)
    {
        // do main task here
        Console.WriteLine("do main task at: " + DateTime.Now);
    }

    public void Start()
    {
        _timer.Start();
    }

    public void Stop()
    {
        _timer.Stop();
    }
}

 

接著再程式進入點就可以使用 HostFactory 掛載 MainService 執行主要工作。

using Topshelf;

namespace TopShelfConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
           {
               x.Service<MainService>(s =>
               {
                   s.ConstructUsing(name => new MainService());
                   s.WhenStarted(ms => ms.Start());
                   s.WhenStopped(ms => ms.Stop());
               });

               x.SetServiceName("SampleServiceName");
               x.SetDisplayName("SampleDisplayName");
               x.SetDescription("SampleDescription");
               x.RunAsLocalSystem();
               x.StartAutomatically();
           });
        }
    }
}

 

直接執行,我們的服務就已經被 Host 到主控台應用程式上執行,而開發人員可以在這個階段就可以直接偵錯;要結束 Service 可以按下 Control + C 即可中斷。

 

 

Windows Service

我們最終的目的就是要服務 Host 在 Windows Service 中,因此可以透過 command line 來執行安裝 / 移除作業,如果需要更多資訊可以輸入 help 參考命令集說明。

 

安裝僅須透過輸入 YourConsoleName.exe install 執行即可

 

 

解除安裝輸入 YourConsoleName.exe uninstall 執行即可

 

 

參考資訊

http://topshelf-project.com/

 

陳志澤