AspNetCore3.1.x以Windows Service运行

AspNetCore3.1.x以Windows Service运行

  1. 安装相应的扩展包

    Nuget install Microsoft.Extensions.Hosting.WindowsServices

  2. 对Pramgram.cs的修改

    public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                var workDir = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);
                Directory.SetCurrentDirectory(workDir);
            }
            CreateHostBuilder(args).Build().Run();
        }
    
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseWindowsService()
    
  3. Publish并以管理员方式管理服务

    # 安装服务
    sc create callboxhubgateway binPath="E:OrangePICallboxCallboxHubGatewayinDebug
    etcoreapp3.1publishcallboxhubgateway.exe" displayName="callboxhubGateway" start=auto
    # 启动服务
    sc start callboxhubgateway
    # 停止服务
    sc stop callboxhubgateway
    # 删除服务
    sc delete callboxhubgateway
    
原文地址:https://www.cnblogs.com/linxmouse/p/14788671.html