Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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" />
like image 202
Luke Vo Avatar asked Jan 21 '26 16:01

Luke Vo


1 Answers

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>();
    })
like image 164
Luke Vo Avatar answered Jan 23 '26 06:01

Luke Vo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!