'Binding section from appsettings.json to options
So I was trying to follow the Microsoft Docs, Options pattern in ASP.NET Core however for the life of me I can't seem to correctly get the "AppSettings" section to my AppSettings object as an option. Configuration.GetSection("AppSettings"); is returning null for me yet
appsettings.Development.json
{
"AppSettings": {
"Secret": "DEVELOPMENTTOKENTEST"
},
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Enrich": [ "FromLogContext", "WithMachineName" ],
"Properties": {
"Application": "Oasis.API"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/api_.log",
"outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 1
}
}
]
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Data Source=JS-PC;Initial Catalog=Oasis;Integrated Security=True"
}
}
Class for my AppSettings section.
public class AppSettings
{
public string Secret { get; set; }
}
How I am trying to read in the section and configure it for dependency injection for use in a service.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
// Configure API secret
var test = Configuration.GetSection("AppSettings"); // null... oh?
services.Configure<AppSettings>(con => Configuration.GetSection("AppSettings").Bind(con));
// Swagger generation
services.AddSwaggerGen();
// Database and Repositories
ConfigureRepositories(services);
// Register Services
ConfigureServiceClasses(services);
}
Here is how I have it setup to take the IOptions in my service.
WebUserService.cs
public class WebUserService : IWebUserService
{
private readonly ILogger<WebUserService> _logger;
private readonly IWebUserRepository _webUserRepository;
private readonly AppSettings _appSettings;
public WebUserService(ILogger<WebUserService> logger, IWebUserRepository webUserRepository, IOptions<AppSettings> appSettings)
{
_logger = logger;
_webUserRepository = webUserRepository;
_appSettings = appSettings.Value;
}
}
Solution 1:[1]
You don't need to setup.Its implementation will be injected by the DI system.You can use following to get the Secret
:
using Microsoft.Extensions.Configuration;
//....
private readonly IConfiguration _mySettings;
public HomeController(IConfiguration mySettings)
{
_mySettings = mySettings;
}
public IActionResult Index()
{
var result = _mySettings.GetValue<string>("AppSettings:Secret");
//...
}
By the way, if you want to inject it,you can use following code.
//...
var settingsSection =Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(settingsSection);
In controller:
private readonly IConfiguration _mySettings;
private readonly AppSettings _settings;
public HomeController(IOptions<AppSettings> settingsAccessor, IConfiguration mySettings)
{
_mySettings = mySettings;
_settings = settingsAccessor.Value;
}
public IActionResult Index()
{
var vm = new AppSettings
{
Secret= _settings.Secret
};
var result = _mySettings.GetValue<string>("AppSettings:Secret");
}
Refer to this thread.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |