Working in a .NET 6 console app and having problem with binding settings from appsettings.json to IOptions.
Here is my code:
appsettings.json
{
"MyOptionsSettings" : {
"Foo": 100,
"Bar": true
}
}
MyOptions.cs
public class MyOptions
{
public int Foo {get; set;}
public bool Bar {get; set;}
}
program.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
var builder = Host.CreateDefaultBuilder(args);
builder.ConfigureServices((hostContext, services) =>
{
var configuration = hostContext.Configuration;
services.Configure<MyOptions>(opts => configuration.GetSection("MyOptionsSettings"));
services.AddTransient<MyService>();
});
var app = builder.Build();
var myService = app.Services.GetService<MyService>();
MyService.cs
public class MyService
{
.
.
public MyService(IOptions<MyOptions> options)
{
_options = options;
}
.
.
}
The _options
has default values for all the properties and nothing from the appsettings. I actually want to use the IOptions<T>
wrapper IOptionsMonitor<T>
so the settings are dynamic. However, I can't even get the IOptions<T>
work. I think my problem is with the IServiceCollection.Configure<T>()
.
Update:
I just came across a blog that probably solved my issue but I'm not sure why the example above isn't. Based on the blog, I changed the following line:
From this:
services.Configure<MyOptions>(opts => configuration.GetSection("MyOptionsSettings"));
To This:
services.Configure<MyOptions>(opts => configuration.GetSection("MyOptionsSettings").Bind(opts));
Now the IOptions binds/resolves without any issues. Even Microsoft's console app documentation uses the one above (without the Bind(opts)
); What's the difference between those two lines?