当使用 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
破坏性变更的类型
此更改为行为更改。
更改原因
此更改通过不重写以前在字典值数组中添加的值来提高绑定行为。
建议的措施
如果新行为不尽如人意,可以在绑定后手动修改数组中的数值。