I'm currently trying to use the default ConfigurationBinder
from AspNetCore 6 especially IConfiguration.Get<T>()
Get<T>()
is used to map a config file section to an object,
but it doesn't work correctly with collections like arrays and lists.
It works fine if there are at least 2 items in the array
but if there's only one item in the array then the mapping doesn't work. This seems to only affect XML
files.
The array can be nested deep inside my sections.
The main problem seems to be that the config keys are generated like this:
collection1:item:myName
for arrays with one element.
vs
collection2:item:0:myName
for arrays with more than one element.
Has anyone a good idea how to accomplish the mapping to arrays inside XML config sections that might have one or more elements?
// Nugets:
// Microsoft.Extensions.Configuration
// Microsoft.Extensions.Configuration.Xml
// Microsoft.Extensions.Configuration.Binder
public void Test()
{
var builder = new ConfigurationBuilder();
builder.AddXmlFile("MyConfig.config");
var config = builder.Build();
var section1 = config.GetSection("collection1");
var section2 = config.GetSection("collection2");
var bound1 = section1.Get<MyObject>(); // ERROR: Mapped to empty List
var bound2 = section2.Get<MyObject>(); // mapped correctly to 2 items
}
public class MyObject
{
public List<MyItem> Item { get; set; }
}
public class MyItem
{
public string MyName { get; set; }
public string MyVal { get; set; }
public override string ToString() => $"{MyName} = {MyVal}";
}
MyConfig.config
<configuration>
<collection1 >
<item myName="MyName1" myVal="MyString1" />
</collection1>
<collection2 >
<item myName="MyName1" myVal="MyString1" />
<item myName="MyName2" myVal="MyString2" />
</collection2>
</configuration>