有没有办法在 .Net Core 的 Windows Worker Services(后台服务)中禁用停止按钮?

Is there a way to disable the stop button in Windows Worker Services (Background Services) in .Net Core?

我将在 Visual Studio 2022 年创建一个 windows 工作人员服务,并根据 Microsoft 的新指南创建 windows 使用 .Net Core 5.0 Windows Service using BackgroundService 服务的服务 Windows Service using BackgroundService

我发现在后台 属性 中没有 属性 来禁用停止按钮 - (缺少 CanStop 属性),就像我们在本机 Windows 使用 .Net Framework 构建的服务。

这个问题是否有解决方法,或者他们会在即将发布的后台服务版本中添加新功能吗?

好吧,如果您调用 UseWindowsService,就会发生这种情况:

public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder)
{
    return UseWindowsService(hostBuilder, _ => { });
}

...

public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder, Action<WindowsServiceLifetimeOptions> configure)
{
    if (WindowsServiceHelpers.IsWindowsService())
    {
        // Host.CreateDefaultBuilder uses CurrentDirectory for VS scenarios, but CurrentDirectory for services is c:\Windows\System32.
        hostBuilder.UseContentRoot(AppContext.BaseDirectory);
        hostBuilder.ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddEventLog();
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddSingleton<IHostLifetime, WindowsServiceLifetime>();
            services.Configure<EventLogSettings>(settings =>
            {
                if (string.IsNullOrEmpty(settings.SourceName))
                {
                    settings.SourceName = hostContext.HostingEnvironment.ApplicationName;
                }
            });
            services.Configure(configure);
        });
    }

    return hostBuilder;
}

WindowsServiceLifetime 实现 ServiceBase,它具有 属性:

https://docs.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.canstop?view=dotnet-plat-ext-6.0

也许你可以这样做:

var host = Host.CreateDefaultBuilder()
    .UseWindowsService()
    .Build();

var windowsServiceLifetime = host.Services.GetService<IHostLifetime>() as WindowsServiceLifetime;

// NOTE .Services.GetService<IHostLifetime>() will return IConsoleLifetime when running under console!
if (windowsServiceLifetime != null)
{
    windowsServiceLifetime.CanStop = false;
}

我不确定这一点,但我做了一些调查,因此 post。如果这没有价值,我会删除它。