使用Topshelf部署.net core windows服务

生来就可爱ヽ(ⅴ<●) 提交于 2020-10-02 08:43:18

使用Topshelf部署.net core windows服务

首先新建一个.net core的模板worker程序

过程 略

打开Program.cs

namespace TopshelfDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }
}

nuget 安装Topshelf

改写下Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<IHost>(s =>
                {
                    s.ConstructUsing(() => CreateHostBuilder(args).Build());
                    s.WhenStarted(service =>
                    {
                        service.Start();
                    });
                    s.WhenStopped(service =>
                    {
                        service.StopAsync();
                    });
                });

                x.StartAutomatically();
                x.RunAsLocalSystem();

                x.SetServiceName("TopshelfDemo.ServiceName");
                x.SetDisplayName("TopshelfDemo.DisplayName");
                x.SetDescription("TopshelfDemo.Description");
            });
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }

该写法的实现原理:通过通用主机方法 IHost 实现管理主机生存期

写法如下:

public class Program
{
    private IHost _host;

    public Program()
    {
        _host = new HostBuilder()
            .Build();
    }

    public async Task StartAsync()
    {
        _host.StartAsync();
    }

    public async Task StopAsync()
    {
        using (_host)
        {
            await _host.StopAsync(TimeSpan.FromSeconds(5));
        }
    }
}

打包

安装 TopshelfDemo

找到相应的文件夹
TopshelfDemo.exe install


启动 TopshelfDemo

TopshelfDemo.exe start

卸载 TopshelfDemo

TopshelfDemo.exe uninstall

.NET 通用主机通用配置

配置Configuration

Host.CreateDefaultBuilder(args)
    .ConfigureHostConfiguration(configHost =>
    {
        configHost.SetBasePath(Directory.GetCurrentDirectory());
        configHost.AddJsonFile("hostsettings.json", optional: true);
        configHost.AddEnvironmentVariables(prefix: "PREFIX_");
        configHost.AddCommandLine(args);
    });

环境名称

Host.CreateDefaultBuilder(args)
    .UseEnvironment("Development")
    //...

logging引入

               .ConfigureLogging((context, logger) =>
                {
                    logger.AddConsole();
                    //logger.AddLog4Net();
                    logger.SetMinimumLevel(LogLevel.Information);
                })

依赖注入

    public class ToDoWork
    {
        public string TimeNow()
        {
            return DateTime.Now.ToString();
        }
    }

program.cs

                .ConfigureServices((hostContext, services) =>
                {
                    services.AddScoped<ToDoWork>();

                    services.AddHostedService<Worker>();
                });

program.cs 最终如下

using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Topshelf;

namespace TopshelfDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<IHost>(s =>
                {
                    s.ConstructUsing(() => CreateHostBuilder(args).Build());
                    s.WhenStarted(service =>
                    {
                        service.Start();
                    });
                    s.WhenStopped(service =>
                    {
                        service.StopAsync();
                    });
                });

                x.StartAutomatically();
                x.RunAsLocalSystem();

                x.SetServiceName("TopshelfDemo.ServiceName");
                x.SetDisplayName("TopshelfDemo.DisplayName");
                x.SetDescription("TopshelfDemo.Description");
            });
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                .UseEnvironment(Environments.Development)
                //.UseEnvironment(Environments.Production)
                //.UseEnvironment(Environments.Staging)
                .ConfigureHostConfiguration(configHost =>
                {
                    configHost.SetBasePath(Directory.GetCurrentDirectory());
                    configHost.AddJsonFile("hostsettings.json", optional: true);
                    configHost.AddEnvironmentVariables(prefix: "PREFIX_");
                    configHost.AddCommandLine(args);
                })
                .ConfigureLogging((context, logger) =>
                {
                    logger.AddConsole();
                    //logger.AddLog4Net();
                    logger.SetMinimumLevel(LogLevel.Information);
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddScoped<ToDoWork>();

                    services.AddHostedService<Worker>();
                });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!