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

问题描述 投票:0回答:3

我想按照使用嵌套字典来填充

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>>

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

c# configuration .net-core-2.1
3个回答
12
投票

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

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();

4
投票

这是我编写的扩展方法,它简化了表示设置的复杂分层对象的传递:

/// <summary>
/// Adds settings to the builder from an anonymous object. This allows complex settings object to be built and passed into here, e.g.
/// <code>
///var settings = new
///{
///  programmeLogin = new[] {
///    new {
///      programmeId = 1,
///      loginOptions = new {
///        loginType = loginType,
///        isDefault = true
///      }
///    }
///  },
///  portal = new {
///    programmeId = 1
///  }
///};
///
///IConfigurationBuilder builder = new ConfigurationBuilder().AddObject(settings);
///IConfigurationRoot configurationRoot = builder.Build();
/// </code>
/// </summary>
/// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
/// <param name="obj">The <see cref="object"/> containing the settings to add.</param>
/// <returns></returns>
public static IConfigurationBuilder AddObject(this IConfigurationBuilder builder, object obj)
{
    string json = System.Text.Json.JsonSerializer.Serialize(obj);

    return builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(json)));
}

1
投票

var inMemConfig = 新字典();

...

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

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

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

[deepNest:1:dict]="secondD"

...

© www.soinside.com 2019 - 2024. All rights reserved.