'IServiceCollection' 不包含 'Configuration' 的定义,即使 IntelliSense 另有建议

'IServiceCollection' does not contain a definition for 'Configuration' even though IntelliSense suggests otherwise

我遇到了一个奇怪的问题。我创建了一个 Worker 项目,以便在 this documentation 之后在 .NET 6 中创建一个 Windows 服务。我想从 appsettings.json 读取设置,所以我添加了以下代码:

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "My Service";
    })
    .ConfigureServices(services =>
    {
        var settings = new ScriptOptions(); // ScriptOptions is just a POCO class
        services.Configuration.Bind(settings);

        services.AddHostedService<WindowsBackgroundService>();
    })
    .Build();

如您所见,IntelliSense 似乎识别出 Configuration 属性 in servicesIServiceCollection 的实例)。

但是,代码无法编译并出现以下错误:

'IServiceCollection' does not contain a definition for 'Configuration' and no accessible extension method 'Configuration' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

我缺少什么包裹?我的项目目前有:

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

看起来 IntelliSense 不知何故被另一个重载弄糊涂了。确实 IServiceCollection does NOT have Configuration property, but HostBuilderContext 确实如此。

ConfigureServices 有另一个公开两个参数的重载。这解决了问题:

    // Add ctx parameter
    .ConfigureServices((ctx, services) =>
    {
        var settings = new ScriptOptions();
        ctx.Configuration.Bind(settings);

        services.AddHostedService<WindowsBackgroundService>();
    })

似乎是 IntelliSense 错误,我报告了它 here