使用.NET Core中的appsettings.json设置继承

时间:2017-07-19 17:21:51

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

我正在努力实现这样的目标:

  • BaseSettings - 具有所有其他部分共有的设置
  • Child1Settings - 具有所有BaseSettings + Child1Settings
  • Child2Settings - 具有所有BaseSettings + Child2Settings

    [...]

  • ChildNSettings - 包含所有BaseSettings + ChildNSettings

那么我的控制器中就有这个:

public class Child1Controller : Controller
{
    public Child1Controller(Child1Settings settings)
    {
        // settings.BaseSetting and settings.Child1Setting should both be accessible here
    }
}

我试过这个:

public class BaseSettings
{
    public string BaseSetting { get; set; }
}

public class Child1Settings : BaseSettings
{
    public string Child1Setting { get; set; }
}

appsettings.json

{
    "BaseSettings": {
        "BaseSetting": "BaseSettingValue"
    },
    "Child1Settings": {
        "Child1Setting": "Child1SettingValue"
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{    
    services.AddOptions();
    services.Configure<Child1Settings>(options => Configuration.GetSection("Child1Settings").Get<Child1Settings>());
    services.AddSingleton(Configuration);
}

填充Child1Settings字段就好了,但不填充BaseSettings字段。我可以看到这个工作(虽然我还没有尝试过),但这感觉很荒谬,如果我有很多孩子设置课程,会导致很多冗余和潜在的错误:

appsettings.json

{
    "Child1Settings": {
        "BaseSettings": {
            "BaseSetting": "BaseSettingValue"
        }
        "Child1Setting": "Child1SettingValue"
    },
    "Child2Settings": {
        "BaseSettings": {
            "BaseSetting": "BaseSettingValue"
        }
        "Child2Setting": "Child2SettingValue"
    }
}

1 个答案:

答案 0 :(得分:0)

实现此目的的一种方法是,为孩子配置基本部分数据,然后为孩子配置特定的数据,如下所示:

services.Configure<Child1Settings>(hostContext.Configuration.GetSection("BaseSettings"));
services.Configure<Child1Settings>(hostContext.Configuration.GetSection("Child1Settings"));

这样,第一次调用Configure<Child1Settings>时,它将使用基本数据进行配置。对Configure<Child1Settings>的下一次调用将覆盖您在BaseSettings中配置的内容,并向其添加其他Child1Settings。