如何在.Net Core中创建分层的内存中配置

时间:2019-03-12 07:03:38

标签: configuration .net-core-2.1

我想通过使用嵌套字典填充IConfiguration来创建分层的内存配置。我目前的方法是这样的。

我有一本这样的字典:

var inMemConfig = new Dictionary<string, object>();
inMemConfig["section1"] = new Dictionary<string, string>();
inMemConfig["section2"] = new Dictionary<string, object>();
inMemConfig["deepNest"] = new Dictionary<string, object>();
// Excluding a cast below: 
inMemConfig["deepNest"]["list"] = new List<Dictionary<string, string>>();
inMemConfig["deepNest"]["dict"] = new Dictionary<string string>();

填充上面的字典后,我尝试使用ConfigurationBuilder,如下所示。

var builder = new ConfigurationBuilder();
var configuration = builder.AddInMemoryCollection(inMemConfig).Build(); 

这显然会给编译器带来错误,inMemConfig的类型必须为:IEnumerable<KeyValuePair<string, string>>

不可能创建分层的内存配置,如果这样的话,任何朝着正确方向的指针都将受到赞赏。谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用冒号(“:”)作为分隔符,以指示配置中的层次结构。例如:

var builder = new ConfigurationBuilder();
var configuration = builder.AddInMemoryCollection(new Dictionary<string, string> {
    ["deepNest:list"] = "some_nested_list_value",
    ["deepNest:dict"] = "some_nested_dict_value"
}).Build();