将Dictionary<string, string>绑定到Configuration Section无效,求助排查
问题分析与解决
错误原因
你搞反了Bind方法的作用方向:Bind是将配置系统中的数据绑定到对象实例,而非把对象的数据写入配置系统。
你原代码里的config.Bind("Section", dict),实际是尝试从配置的Section节点读取数据填充到dict,但此时Section节点是空的,所以dict并没有被修改;同时配置系统会创建Section节点(即使没有内容),这就是第一个断言成功、第二个断言失败的原因。
正确实现方式
如果要让配置的Section节点包含字典中的键值对,有两种常用方式:
方式一:初始化配置时传入带路径的键值对
直接在AddInMemoryCollection中传入符合配置路径格式的键值对(用冒号:分隔层级):
[TestFixture] public class When_binding_a_configuration_section { [Test] public void should_contain_section() { // 初始化时传入带Section路径的键值对 var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string> { { "Section:Key", "Value" } }) .Build(); var dict = new Dictionary<string, string>(); // 将Section节点的数据绑定到字典 config.GetSection("Section").Bind(dict); var section = config.GetSection("Section"); section.GetSection("Section").ShouldNotBeNull(); // 仍成功 section["Key"].ShouldBe("Value"); // 现在断言成功 } }
方式二:手动给配置节点赋值
直接获取Section节点后,手动设置其下的键值对:
[TestFixture] public class When_binding_a_configuration_section { [Test] public void should_contain_section() { var config = new ConfigurationBuilder() .AddInMemoryCollection() .Build(); var section = config.GetSection("Section"); // 直接给Section节点下的Key赋值 section["Key"] = "Value"; var dict = new Dictionary<string, string>(); section.Bind(dict); section.GetSection("Section").ShouldNotBeNull(); // 成功 section["Key"].ShouldBe("Value"); // 成功 dict["Key"].ShouldBe("Value"); // 字典也能正确获取值 } }
内容的提问来源于stack exchange,提问作者Alexander Zeitler
相关产品推荐
相关产品推荐

