我想通过使用嵌套字典填充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>>
。
不可能创建分层的内存配置,如果这样的话,任何朝着正确方向的指针都将受到赞赏。谢谢。
答案 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();