将配置绑定到字典扩展值

当使用值为可变集合类型的 Dictionary<TKey,TValue> 对象绑定配置时,多次绑定到同一键会扩展值集合,而不是将整个集合替换为新值。

引入的版本

.NET 7

旧行为

请考虑以下代码,该代码将包含名为 Key 的单个键的配置多次绑定到字典。

using Microsoft.Extensions.Configuration;

IConfiguration config = new ConfigurationBuilder()
    .AddInMemoryCollection()
    .Build();

config["Key:0"] = "NewValue";
var dict = new Dictionary<string, string[]>() { { "Key", new[] { "InitialValue" } } };

Console.WriteLine($"Initially: {String.Join(", ", dict["Key"])}");
config.Bind(dict);
Console.WriteLine($"Bind: {String.Join(", ", dict["Key"])}");
config.Bind(dict);
Console.WriteLine($"Bind again: {String.Join(", ", dict["Key"])}");

在 .NET 7 之前,每次绑定时 Key 的值都会被覆盖一次。 该代码生成的输出如下所示:

Initially: InitialValue
Bind: NewValue
Bind again: NewValue

新行为

从 .NET 7 开始,每次绑定同一键时都会扩展字典值,不但会添加新值,还会保留数组中的任何现有值。 旧行为部分中的相同代码会生成以下输出:

Initially: InitialValue
Bind: InitialValue, NewValue
Bind again: InitialValue, NewValue, NewValue

中断性变更的类型

此更改为行为更改

更改原因

此更改通过不覆盖字典值数组中之前添加的值来改进绑定行为。

如果新行为不尽如人意,则可以在绑定后手动操作数组中的值。

受影响的 API