如何使用Topshelf與.NET泛型主機創建Windows服務

1 前置閱讀

在閱讀本文章以前,你能夠先閱讀:框架

  • Topshelf一個用於使用.NET構建Windows服務框架

2 使用

2.1 建立應用程序

首先,建立一個新的控制檯應用程序並從nuget獲取Topshelf和Microsoft.Extensions.Hosting軟件包ui

Topshelf
Microsoft.Extensions.Hosting

固然咱們也須要安裝Serilog相關的日誌框架。this

Serilog.Extensions.Hosting
Serilog.Settings.Configuration
Serilog.Sinks.Console
Serilog.Sinks.File
Topshelf.Serilog

2.2 建立.NET泛型主機

而後,咱們先創建CreateHostBuilder()方法,並加載了Serilog日誌並依賴注入MyService和AppSettings,MyService類作爲Topshelf所使用的主要邏輯程序,它會提供Start()和Stop()作爲Topshelf執行或中止主要邏輯程序的動做。日誌

class Program
{
    static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureServices((hostContext, services) =>
            {
                services.Configure<AppSettings>(hostContext.Configuration);
                services.AddTransient<MyService>();
            });
}

2.3 在Topshelf中註冊服務

接着,在Topshelf中註冊咱們的服務類。跳轉到Program.cs並添加:code

class Program
{
    static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        RunWindowsServiceWithHost(host);
    }

    private static void RunWindowsServiceWithHost(IHost host)
    {
        var rc = HostFactory.Run(x =>
        {
            x.UseSerilog();
            x.SetDisplayName("個人服務");
            x.SetDescription("個人服務詳細描述");
            x.SetServiceName("MyService");

            var myService = host.Services.GetRequiredService<MyService>();
            x.Service<MyService>(s =>
            {
                s.ConstructUsing(() => myService);
                s.WhenStarted(tc => tc.Start());
                s.WhenStopped(tc => tc.Stop());
            });
            x.RunAsLocalSystem();
            x.StartAutomatically();
        });

        var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
        Environment.ExitCode = exitCode;
    }
}

2.4 MyService類

接着,咱們看看MyService類,主要演示了注入ILogger和AppSettings。orm

public class MyService
{
    private readonly ILogger logger;
    private readonly AppSettings settings;

    public MyService(IOptions<AppSettings> settings, ILogger<MyService> logger)
    {
        this.settings = settings.Value;
        this.logger = logger;
    }
    public void Start()
    {
        logger.LogInformation($"Starting {this.settings.ServiceName}...");
    }

    public void Stop()
    {
        logger.LogInformation($"Stopping {this.settings.ServiceName}...");
    }
}

2.5 運行應用程序

最後,F5執行應用程序,若是一切順利,你應該會看到相似如下內容的信息:
imageip

相關文章
相關標籤/搜索