Search code examples
c#.netconfigurationwindows-services.net-6.0

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


I am having a strange problem here. I created a Worker project in order to create a Windows Service in .NET 6 following this documentation. I want to read the settings from appsettings.json so I added the following code:

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();

As you can see, IntelliSense seems to recognize there is Configuration property in services (instance of IServiceCollection).

enter image description here

However, the code wouldn't compile with this error:

'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?)

What package am I missing? My project currently has:

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

Solution

  • They fixed the bug. To access Configuration or other IHostBuilderContext members, use this overload:

        .ConfigureServices((ctx, services) =>
        {
            var settings = new ScriptOptions();
            ctx.Configuration.Bind(settings);
    
            services.AddHostedService<WindowsBackgroundService>();
        })
    

    Original answer:

    Seem to be an IntelliSense bug, I reported it here on VS Developer community here. If you encounter the same problem, please upvote it.

    Looks like somehow IntelliSense was confused by the other overload. Indeed IServiceCollection does NOT have Configuration property, but HostBuilderContext does.

    ConfigureServices has another overload that expose both parameters. This fixes the problem:

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