Search code examples
c#.net.net-coreconfigurationstartup

Can I get bound configuration values from a .net HostApplicationBuilder?


Consider the following setup for a console application.

appsettings.json:

{
  "MySettings": {
    "MyValue": "Foo"
  }
}

MySettings.cs

public class MySettings
{
    public string MyValue { get; set; }
}

And then in the console app itself:

public static async Task Main(string[] args)
{
    var builder = Host.CreateApplicationBuilder(args);

    builder.Services
        .AddOptions<MySettings>()
        .BindConfiguration("MySettings");

    await builder.Build().RunAsync();
}

Inside the Main method and after I've created the builder, I can access my config value by using:

var foo = builder.Configuration.GetValue<string>("MySettings:MyValue");

But is there any way I can access that value through an instance of the MySettings class? Does the builder make it available in any way after it's been bound?


Solution

  • AddOptions is used to register settings via options pattern (though usually I prefer Configure for registration - builder.Services.Configure<MySettings>(builder.Configuration.GetSection("MySettings"))), so you need to access it accordingly, for example by resolving IOptions<MySettings>. For example (just for demonstration, usually you will inject corresponding IOptions, IOptionsMonitor or IOptionsSnapshot in service which needs access to them):

    var build = builder.Build();
    var options = build.Services.GetRequiredService<IOptions<MySettings>>();
    var valueMyValue = options.Value.MyValue; // Foo
    await build.RunAsync();
    

    Read more: