如何通过绑定读取数组配置部分?
如何使用 Microsoft.Extensions.Configuration 和绑定读取配置值数组?
例如,给定以下 XML 配置:
<root>
<eventConfiguration>
<event name="0" source="" type="" target="" />
<event name="1" source="" type="" target="" />
<event name="2" source="" type="" target="" />
</eventConfiguration>
</root>
和以下类:
public class Configuration
{
public EventConfiguration EventConfiguration {get; set;}
}
public class EventConfiguration
{
public List<Event> Events {get; set;}
}
public class Event
{
public string Name {get; set;}
public string Source {get; set;}
public string Type {get; set;}
public string Target {get; set;}
}
当我尝试获取 Configuration 的实例时,事件列表为 null:
IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddXmlFile("default.xml");
var root = builder.Build();
// with binding
var configuration = root.Get<Configuration>();
var events = configuration.EventConfiguration.Events; // null
// without binding
var eventSource = root.GetValue("eventConfiguration:event:0:source", default(string)); // not null
How can I read an array of configuration values using Microsoft.Extensions.Configuration with binding?
For example, given the following XML configuration:
<root>
<eventConfiguration>
<event name="0" source="" type="" target="" />
<event name="1" source="" type="" target="" />
<event name="2" source="" type="" target="" />
</eventConfiguration>
</root>
And the following classes:
public class Configuration
{
public EventConfiguration EventConfiguration {get; set;}
}
public class EventConfiguration
{
public List<Event> Events {get; set;}
}
public class Event
{
public string Name {get; set;}
public string Source {get; set;}
public string Type {get; set;}
public string Target {get; set;}
}
When I try to get an instance of Configuration the Event-List is null:
IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddXmlFile("default.xml");
var root = builder.Build();
// with binding
var configuration = root.Get<Configuration>();
var events = configuration.EventConfiguration.Events; // null
// without binding
var eventSource = root.GetValue("eventConfiguration:event:0:source", default(string)); // not null
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案是将
ConfigurationKeyNameAttribute
添加到Events
属性,因为 XML 元素的名称是event
而不是events
。更新#1:
这是我的有效代码。
ConsoleApp1.csproj
default.xml
Program.cs
输出为:
The solution is to add
ConfigurationKeyNameAttribute
to theEvents
property as your XML element's name isevent
notevents
.Update #1:
This is my code that works.
ConsoleApp1.csproj
default.xml
Program.cs
The output is: