1. 程式人生 > >使用.NET Core建立Windows服務詳細步驟

使用.NET Core建立Windows服務詳細步驟

[toc] --- ### #建立步驟 使用該方式建立,首先要確保你已經安裝了.NET Core 3.0或以上版本 . 但是如果你想要在.NET Core 2.x專案中使用這個方式,應該是行不通的。 #### 1、使用Visual Studio建立 開啟Visual Studio,建立新專案,找到Worker Service模板。 ![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201023121907650.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dpbGxpbmd0b2xvdmU=,size_16,color_FFFFFF,t_70#pic_center) #### 2、使用命令列建立 ```bash dotnet new worker ``` ### #專案結構說明 創建出來的專案,包含兩個主要檔案。其中Program.cs檔案是應用的啟動“載入程式”。另外一個檔案是worker.cs檔案,在這個檔案中,你可以編寫你的服務邏輯。同時在依賴項的包中引入了Microsoft.Extensions.Hosting包。 ![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201023122955971.png#pic_center) ### #將應用轉換成Window服務 當前專案可在linux下完美執行,但是還不能以服務的方式在windows上安裝執行。 #### 1、引入Microsoft.Extensions.Hosting.WindowsServices 為了將應用轉換成Windows服務,我們需要使用如下命令引入一個包。 ```bash Install-Package Microsoft.Extensions.Hosting.WindowsServices ``` ![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201023123938599.png#pic_center) #### 2、修改程式碼 需要修改Program.cs檔案,新增UseWindowsService()方法的呼叫。 ```csharp public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) { var host = Host.CreateDefaultBuilder(args); //判斷當前系統是否為windows if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { host.UseWindowsService(); } return host.ConfigureServices((hostContext, services) => { services.AddHostedService(); }); } } ``` 程式碼中增加了對作業系統的判斷,從而可以相容windows和linux。 #### 3、釋出 使用Visual Studio釋出: ![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201023135559181.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dpbGxpbmd0b2xvdmU=,size_16,color_FFFFFF,t_70#pic_center) 使用命令列釋出: ```bash dotnet publish -r win-x64 -c Release ``` #### 4、使用SC命令在windows上安裝服務 ```bash sc create TestService BinPath=D:\dir\WindowsServiceExample.exe ``` 也可以建立一個bat檔案,用來安裝windows服務,如下: ```bash @echo off @title 安裝windows服務 @echo off echo= 安裝服務! @echo off @sc create worktest binPath= "%~dp0WorkerService1.exe" echo= 啟動服務! @echo off @sc start worktest @echo off echo= 配置服務! @echo off @sc config worktest start= AUTO @echo off echo= 成功安裝、啟動、配置服務! @pause ``` 將bat檔案放到服務檔案同目錄,修改下服務名和exe名字即可雙擊執行安裝。 SC其他操作服務的常用命令: ```bash sc start TestService sc stop TestService sc delete TestService ``` ---