1

In a console application, rather than building the IConfiguration and IServiceProvider manually, I'm trying to use the Host.CreateDefaultBuilder() process:

IHost host = Host.CreateDefaultBuilder()
    .ConfigureServices((context, services) =>
    {
        services.AddSingleton<Whatever>();
    })
    .Build();

I can get the configuration object after building the host. But what I'm looking for is a way to get the config object while still in the ConfigureServices body, so that I can bind a config section to the service provider.

Something like:

AccountConfiguration accountConfig = new();
config.Bind("AccountConfiguration", accountConfig);
services.AddSingleton(accountConfig);
// or
services.Configure<AccountConfiguration>(config.GetSection("AccountConfiguration"));

Is there a way to access the config object while still configuring the services? Or a good way of adding an object to the service collection after the host has already been built?

1 Answer 1

4

The first parameter of lambda passed to ConfigureServices is HostBuilderContext which exposes configuration property - IConfiguration Configuration:

IHost host = Host.CreateDefaultBuilder()
    .ConfigureServices((context, services) =>
    {
        IConfiguration config = context.Configuration;
        // use config
        services.AddSingleton<Whatever>();
    })
    .Build();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.