Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access configuration object while configuring services

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

IHost host = Host.CreateDefaultBuilder()
    .ConfigureServices((context, services) =>
    {
        var config = context.Configuration;
        // use config
        services.AddSingleton<Whatever>();
    })
    .Build();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading