如何在Asp.Net MVC 6中检索AppSettings配置?

假设我使用新的DepencyInjection框架在新的ASP.Net/vNext中配置我的类和依赖项。

我该如何使用,如何获取预定义的配置设置?

public void ConfigureServices(IServiceCollection services) { // Add Application settings to the services container. services.Configure(Configuration.GetSubKey("AppSettings")); // Add EF services to the services container. services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); // Add Identity services to the services container. services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); // Configure the options for the authentication middleware. // You can add options for Google, Twitter and other middleware as shown below. // For more information see http://go.microsoft.com/fwlink/?LinkID=532715 services.Configure(options => { options.AppId = Configuration["Authentication:Facebook:AppId"]; options.AppSecret = Configuration["Authentication:Facebook:AppSecret"]; }); services.Configure(options => { options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"]; options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]; }); // Add MVC services to the services container. services.AddMvc(); services.AddSingleton(a => { //AppSettings settingsModel = ?? //GET CONFIGURATION SETTINGS FILLED // TECHNICAL ARTIFICE TO RETRIEVE CURRENT SETTINGS //var settingsModel = new AppSettings(); //var config = Configuration.GetSubKey("AppSettings"); //foreach (var item in typeof(AppSettings).GetProperties().Where(b => b.CanWrite)) { //item.SetValue(settingsModel, config.Get(item.Name)); } return new FooService(settingsModel); }); //Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. //You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. services.AddWebApiConventions(); } 

您可以通过在其构造函数中注入IOptions DI服务,在您的FooService中获取AppSettings。

IOptions<>接口是名为Options Model的一部分,用于在整个应用程序中访问POCO样式设置(例如:您的AppSettings)。 像services.Configure(这样的调用services.Configure(以及services.Configure(options =>上面例子中的services.Configure(options => ,实际上注册了DI服务,而DI服务在解析IOptions<>请求时会被称为OptionsManager的DI服务使用)。

例:

 public class FooService { private readonly AppSettings _settings; public FooService(IOptions options) { _settings = options.Options; } .... .... }