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;
}
}