1 前置閱讀
在閱讀本文章之前,你可以先閱讀:
- Topshelf一個用於使用.NET構建Windows服務框架
2 使用
2.1 建立應用程式
首先,建立一個新的控制檯應用程式並從nuget獲取Topshelf和Microsoft.Extensions.Hosting軟體包
Topshelf
Microsoft.Extensions.Hosting
當然我們也需要安裝Serilog相關的日誌框架。
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並新增:
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。
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執行應用程式,如果一切順利,你應該會看到類似以下內容的資訊: