ASP.NET Core 6 应用找不到 UseWindowsService

ASP.NET Core 6 app not able to find UseWindowsService

我的 objective 是以最简单的方式 运行 一个 ASP.NET Core 6 应用程序作为 Windows 服务,我理解使用下面显示的代码。

我已经包含了这两行(尽管只有顶部是必需的):

using Microsoft.AspNetCore.Hosting.WindowsServices;
using Microsoft.Extensions.Hosting.WindowsServices;

并安装了 nuget 包:

<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="6.0.0" />

但是这段代码在使用IWebHostBuilder时无法解析.UseWindowsService():

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseConfiguration(Configuration)
            .ConfigureServices(ConfigureServices)
            .UseUrls(Configuration.GetBindHostUrl())
            .UseStartup<Startup>()
            .UseWindowsService();   // not found

我得到的错误是:

'IWebHostBuilder' does not contain a definition for 'UseWindowsService' and the best extension method overload 'WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder)' requires a receiver of type 'IHostBuilder'

我在这里错过了什么?

您可以尝试使用更通用的 IHostBuilder:

而不是使用 WebHost
 var host = Host.CreateDefaultBuilder(args)
                .UseWindowsService()
                .UseSystemd()
                .ConfigureWebHostDefaults(webbuilder =>
                {
                    //Configure here your WebHost. For example Startup;
                    webbuilder.UseStartup<Startup>();
            });