我使用一个.NET工作人员在Windows中创建了一个Windows (也在.NET 5中),使用IHostBuilder.UseWindowsService()调用作为Windows运行它。
我的问题是,如何捕获Windows命令,例如
sc.exe control <my service name> 200
据我所知,我无法用这种构建Windows的新方法捕获到与旧的ServiceBase.OnCustomCommand相同的内容。
任何关于如何捕获这些命令的帮助都将不胜感激。即使答案是“回到Windows中使用ServiceBase”。
谢谢!
发布于 2021-07-15 10:58:39
对于那些还在寻找答案的人来说。有关解决方案,请参见关于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;
}
}https://stackoverflow.com/questions/65585865
复制相似问题