With .NET-Core apps the configuration data read from some file/environment is loaded into an IConfigurationRoot
instance. But I keep seeing examples that show that the injected instance is an IOptions<T>
.. not an IConfigurationRoot
.
- Why
IOptions
? - What is the advantage of this class instead of just having my own
AppSettings
POCO? - Do I need to do it this way? Is there another way?
For example..
public static IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
.AddJsonFile("appSettings.json", true, true)
.AddJsonFile($"appSettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
// Register the IConfiguration instance which MyOptions binds against.
services.Configure<AppConfiguration>(Configuration);
// <snip other stuff>
}
public AccountController(IOptions<AppConfiguration> appConfiguration)
{
// do stuff with appConfiguration here.
}