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

9
假设我正在使用新的DepencyInjection框架来配置我的类和依赖项在新的ASP.Net/vNext中。那么,我该如何使用并获取我预定义的配置设置呢?
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Application settings to the services container.
        services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));

        // Add EF services to the services container.
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
        // Add Identity services to the services container.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .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<FacebookAuthenticationOptions>(options =>
        {
            options.AppId = Configuration["Authentication:Facebook:AppId"];
            options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
        });

        services.Configure<MicrosoftAccountAuthenticationOptions>(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();
    }

也许我误解了问题,但我没有看到问题所在。为什么不直接将Configuration.GetSubKey("AppSettings")传递到FooService构造函数中呢? - Aluan Haddad
由于在项目中默认创建了 AppSettings 类,它只是用于配置,并且如果我使用 Configuration.GetSubKey,我将获得一个 IConfiguration 对象,这意味着我需要手动获取配置值。 - J. Lennon
可能是[ASP.Net Core MVC依赖注入不起作用]的重复问题(https://dev59.com/4loV5IYBdhLWcg3wA66x)。 - Michael Freidgeim
1个回答

9
您可以通过在FooService的构造函数中注入> DI服务来获取AppSettings。 IOptions<>接口是Options Model的一部分,用于在应用程序中访问POCO样式的设置(例如您的AppSettings)。 像上面示例中的services.Configure和services.Configure(options =>之类的调用实际上注册DI服务,这些DI服务反过来由名为OptionsManager的DI服务在解析对IOptions<>的请求时使用。 示例:
public class FooService
{
    private readonly AppSettings _settings;

    public FooService(IOptions<AppSettings> options)
    {
        _settings = options.Options;
    }

    ....
    ....
}

2
对于 1.0.0-rc1 版本,请将 options.Options 更改为 options.Value - meze
如何在我的代码中使用此服务?FooService fooService = new FooService() - MichaelMao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接