Reputation: 79
I am converting an MVC 5 application to Core 2, and am confused over the settings.
I have a service that connects to an API server; The API server address is stored in a AppSettings.json configuration file as there is a development and production version.
"EtimeSettings": {
"Api_Server": "123.123.123.123"
}
Having read some blogs, I have added the following code to startup.cs ConfigureServices
:
services.AddMvc();
var eTimeSettings = new EtimeSettingsModel();
Configuration.Bind("EtimeSettings", eTimeSettings);
services.AddSingleton(eTimeSettings);
I cannot figure out how to retrieve these values in my API Service.
I was though able to retrieve the values using the following code;
public string GetApiServer()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
EtimeSettingsModel et = new EtimeSettingsModel();
IConfiguration Configuration = builder.Build();
Configuration.GetSection("EtimeSettings").Bind(et);
var apiServer = Configuration["EtimeSettings:Api_Server"];
return apiServer;
}
But I really don't believe that this is the best way.
What am I missing?
Upvotes: 1
Views: 653
Reputation: 247098
Referencing Options pattern in ASP.NET Core Documentation
Assuming
public class EtimeSettingsModel {
public string Api_Server { get; set; }
}
To setup the
IOptions<TOptions>
service you call theAddOptions
extension method during startup in yourConfigureServices
method. You configure options using theConfigure<TOptions>
extension method. You can configure options using a delegate or by binding your options to configuration:
public void ConfigureServices(IServiceCollection services) {
//...
// Setup options with DI
services.AddOptions();
// Configure EtimeSettingsModel using config by installing
// Microsoft.Extensions.Options.ConfigurationExtensions
// Bind options using a sub-section of the appsettings.json file.
services.Configure<EtimeSettingsModel>(Configuration.GetSection("EtimeSettings"));
services.AddMvc();
//...
}
Options can be injected into your application using the
IOptions<TOptions>
accessor service.
private readonly EtimeSettingsModel eTimeSettings;
public MyAPIService(IOptions<EtimeSettingsModel> eTimeSettings) {
this.eTimeSettings = eTimeSettings.Value;
}
Upvotes: 2