为什么ASP.NET-Core应用程序'Configuration / AppSettings'POCO作为IOptions <t>传递而不仅仅是T?

时间:2017-05-24 14:03:47

标签: c# asp.net .net asp.net-core

使用.NET-Core应用程序,configuration data read from some file/environment将加载到IConfigurationRoot实例中。但我不断看到示例表明注入的实例是IOptions<T> ..而不是IConfigurationRoot

  • 为什么IOptions
  • 这个班的优点是什么,而不仅仅是拥有自己的AppSettings POCO?
  • 我需要这样做吗?还有另一种方式吗?

例如......

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

0 个答案:

没有答案