0

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.
}
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • See [my answer](https://stackoverflow.com/a/41151115/455493) on this question. Technically you can't do w/o, but you won't be able to update it when the appsettings.json gets changed – Tseng May 24 '17 at 14:08
  • In my opinion, `IOptions` have some disanvantages so we use pure POCOs as described here: https://stackoverflow.com/q/43679665/5112433 – Ilya Chumakov May 24 '17 at 15:05

0 Answers0