Dotnet Core 3.1 appsettings mapping with IOptions, IOptionsSnapshot and IOptionsMonitor
Check official documentation here
For a behaviour summary for each interface see here
Usage
I prefer to create a section called Settings
to keep all the parameters, so I’ll follow this approach.
Define AppSettings (or you name it) class
class AppSettings
{
public string AadTenantName { get; set; }
public string AadClientApplicationId { get; set; }
}
Create corresponding parameters in appsettings.json
{
"Logging": {
"LogLevel": {
.....
}
},
"AllowedHosts": "*",
"Settings": {
"AadTenantName": "comercia.onmicrosoft.com",
"AadClientApplicationId": "5e416176-9f18-4a96-9ce3-97f27599fb20"
}
}
Register section to be loaded
// Startup.ConfigureServices(...)
services.Configure<AppSettings>(Configuration.GetSection("Settings"));
Access settings
Here inject IOptions, IOptionsSnapshot or IOptionsMonitor based on behaviour requirements.
[ApiController]
[Route("[controller]")]
public class AppSettingsController : ControllerBase
{
private readonly AppSettings _appSettings;
public AppSettingsController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok(await Task.FromResult(_appSettings));
}
}