Home > database >  Access configuration object while configuring services
Access configuration object while configuring services

Time:11-19

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?

CodePudding user response:

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