在ASP.NET Core中注册子IOptions

时间:2016-04-07 10:07:16

标签: asp.net configuration asp.net-core asp.net-core-mvc options

我有以下配置设置:

public void ConfigureServices(IServiceCollection services)
{
    var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    services.Configure<AppSettings>(configuration);
}

public class AppSettings
{
    public ChildSettings Child { get; set; }

    public string Property { get; set; }
}

public class ChildSettings
{
    public string ChildProperty { get; set; }
}

我的appSettings.json看起来像这样:

{
    "Child": {
        "ChildProperty": "Value"
    }
    "Property": "Value"
}

我可以将IOptions<AppSettings>注入我的控制器中:

public class MyController : Controller
{
    public MyController(IOptions<AppSettings> options)
    {
        ChildSettings appSettings = options.Value;
    }
}

它有点老了,不得不走几层才能到达你想要的设置对象。有没有办法像我这样使用IOptions<ChildSettings>

public class MyController : Controller
{
    public MyController(IOptions<ChildSettings> options)
    {
        ChildSettings appSettings = options.Value;
    }
}

2 个答案:

答案 0 :(得分:2)

If you want to use ChildSettings directly without going via the AppSettings object, you must register ChildSettings as a separate entry in your DI configuration like this:

services.Configure<ChildSettings>(_configuration.GetSection("AppSettings:ChildSettings"));

But if you want to do this, perhaps you could just have ChildSettings at the root level of your appsettings.json file? You are not required to have your settings in a section named AppSettings.

答案 1 :(得分:0)

配置所有options automatically

PM> Install-Package Register.Options.Asp.Net.Core

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureOptionsFromAssemblies(configuration, new List<Assembly>()
    {
        typeof(AppSettings).Assembly
    });

    ...
}

appsettings.json

{
    "ChildSettings": {
        "ChildProperty": "Value"
    }       
}

免责声明package

的作者