问题描述
我使用 BackgroundService
工作器在 .NET Core(也在 .NET 5 中)创建了一个 Windows 服务,并使用 IHostBuilder.UseWindowsService()
调用将其作为 Windows 服务运行。
我的问题是,如何捕获 Windows 服务命令,例如
sc.exe control <my service name> 200
据我所知,在这种构建 Windows 服务的新方式中,我无法捕捉到与旧的 ServiceBase.OnCustomCommand
相同的东西。
任何有关如何捕获这些命令的帮助将不胜感激。即使答案只是“回到为您的 Windows 服务使用 ServiceBase”。
谢谢!
解决方法
对于仍在寻找答案的任何人。请参阅 this answer on github 以获取解决方案
基本上是要注册一个自定义的 IHostLifetime
实现:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext,services) =>
{
if (WindowsServiceHelpers.IsWindowsService())
services.AddSingleton<IHostLifetime,CustomService>();
})
实际实现可能继承自 WindowsServiceLifetime
,您可以在其中覆盖 OnCustomCommand
方法:
/// <summary>
/// Will handle custom service commands
/// </summary>
/// <param name="command">The command message sent to the service.</param>
protected override void OnCustomCommand(int command)
{
_logger.LogInformation("Received custom service control command: {0}",command);
switch (command)
{
case PreShutdownCommandCode:
// Handle your custom command code
break;
default:
base.OnCustomCommand(command);
break;
}
}