Dotnet Core 3.1 appsettings mapping with IOptions, IOptionsSnapshot and IOptionsMonitor
Map appsettings.json to strongly-typed classes using the Options pattern. For behavior differences between IOptions, IOptionsSnapshot, and IOptionsMonitor, see the official documentation.
Define the settings class
class AppSettings
{
public string AadTenantName { get; set; }
public string AadClientApplicationId { get; set; }
}
Add settings to appsettings.json
{
"Logging": {
"LogLevel": {
.....
}
},
"AllowedHosts": "*",
"Settings": {
"AadTenantName": "comercia.onmicrosoft.com",
"AadClientApplicationId": "5e416176-9f18-4a96-9ce3-97f27599fb20"
}
}
Register the configuration section
// Startup.ConfigureServices(...)
services.Configure<AppSettings>(Configuration.GetSection("Settings"));
Inject and use
Choose IOptions, IOptionsSnapshot, or IOptionsMonitor based on your 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));
}
}