Search code examples
.net-coredependency-injection

How to get value from Configuration object via HostBuilder?


Started a new Console app in .NET 6 and am adding Dependency Injection. In the code below, how can I get access to the IConfiguration object to read a value from appsettings (after calling Build?

The configuration is available within the StoreFactory service, as its injected via the constructor, but if I want to read values from appsettings within the main section of code within program.cs, how can I get at it?

program.cs

var SvcBuilder = new HostBuilder()
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.SetBasePath(Directory.GetCurrentDirectory());
        config.AddJsonFile("appsettings.json", optional: true);
        config.AddEnvironmentVariables();
        
        if (args != null)
        {
            config.AddCommandLine(args);
        }
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddLogging(configure => configure.AddConsole())
        .AddTransient<IStoreFactory, StoreCtxFactory>();
    });

var host = SvcBuilder.Build();

Solution

  • The Host.CreateDefaultBuilder defines the behavior to discover the JSON configuration and expose it through the IConfiguration instance. From the host instance, you can ask the service provider for the IConfiguration instance and then ask it for values.

    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    using IHost host = Host.CreateDefaultBuilder(args).Build();
    
    // Ask the service provider for the configuration abstraction.
    IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
    
    // Get values from the config given their key and their target type.
    var configValueInt = config.GetValue<int>("yourKeyName");
    string configValueStr = config.GetValue<string>("yourKeyName");
    

    For more information read the Docs.