常用的windows服務開發有vs自帶的windows服務開發,但是操作起來不是很便利,相比Topshelf後者更加的方便,且易於調試,安裝,卸載.
1、安裝
通過nuget搜索最新版本的topshelf,並安裝到控制檯項目(netcore和net均可)中,一般都是用控制檯調試,然後通過topshelf安裝成windows服務.
官方文檔地址 組件支持的功能基本滿足日常開發需求,如常規的服務描述,服務異常處理,服務恢復,服務啓動模式等等不一一贅述,自行查閱文檔.
2、代碼
public static void Run<TExecutedService>(Action<TopshelfOptions> configurator) where TExecutedService : TopshelfService { var options=new TopshelfOptions(); configurator?.Invoke(options); if (string.IsNullOrEmpty(options.ServiceName)) throw new ArgumentNullException(nameof(options.ServiceName)); if (string.IsNullOrEmpty(options.DisplayName)) throw new ArgumentNullException(nameof(options.DisplayName)); HostFactory.Run(configurater => { configurater.Service<TExecutedService>(service => { service.ConstructUsing(hostSetting => { return ApplicationConfiguration.Current.Provider.GetRequiredService<TExecutedService>(); }); service.WhenStarted(s => s.Start()); service.WhenStopped(s => s.Stop()); }); configurater.RunAsLocalSystem(); configurater.SetDescription(options.Description?? options.DisplayName); configurater.SetDisplayName(options.DisplayName); configurater.SetServiceName(options.ServiceName); configurater.OnException(exception => { Console.WriteLine("業務執行異常,異常信息如下:" + exception.Message + "堆棧信息如下:" + exception.StackTrace); }); }); }