I am trying to learn ASP.NET 5. I am using it on Mac OS X. At this time, I have a config.json file that looks like the following:
config.json
In your Startup class, first specify your configuration sources:
private readonly IConfiguration configuration;
public Startup(IHostingEnvironment env)
{
configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
}
The env.EnvironmentName is something like "development" or "production". Suppose it is "development". The framework will try to pull configuration values from config.development.json first. If the requested values aren't there, or the config.development.json file doesn't exist, then the framework will try to pull the values from config.json.
Configure your config.json sections as services like this:
public void ConfigureServices(IServiceCollection services)
{
services.Configure(configuration.GetSubKey("AppSettings"));
services.Configure(configuration.GetSubKey("DbSettings"));
services.Configure(configuration.GetSubKey("EmailSettings"));
}
Calling Configure on the IServiceCollection registers the type IOptions in the dependency injection container. Note that you don't need your AppConfiguration class.
Then specify dependencies to be injected like this:
public class EmailController : Controller
{
private readonly IOptions emailSettings;
public EmailController (IOptions emailSettings)
{
this.emailSettings = emailSettings;
}
public IActionResult Index()
{
string apiKey = emailSettings.Options.EmailApiKey;
...
}
}