【问题标题】:How to create a hierarchical in-memory configuration in .Net Core如何在 .Net Core 中创建分层内存配置
【发布时间】:2021-10-19 08:43:22
【问题描述】:

我想按照使用嵌套字典填充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&lt;KeyValuePair&lt;string, string&gt;&gt;。

是否不可能创建分层内存配置,如果是这样,任何指向正确方向的指针都非常感谢。谢谢。

【问题讨论】:

    标签: configuration .net-core-2.1


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

      var inMemConfig = new Dictionary();

      ...

      [deepNest:0:list]="firstL",

      [deepNest:1:list]="secondL",

      [deepNest:0:dict]="firstD",

      [deepNest:1:dict]="secondD"

      ...

      【讨论】:

        猜你喜欢
        • 2019-04-22
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-22
        • 2022-06-24
        • 2021-09-19
        • 1970-01-01
        相关资源
        最近更新 更多