How to bind configuration to Dictionary<string, ValueTuple>() #95181
-
Considering: using System.Collections.Generic;
var configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
var parent = configuration.Get<Parent>();
var count = parent.Children.Count; // 2, it's ok
var value = parent.Children["1"]; // (null, null)
public class Parent
{
public IDictionary<string, (Child1 Child1, Child2 Child2)> Children { get; set; }
// other props
}
public class Child1
{
public string A { get; set; }
}
public class Child2
{
public string B { get; set; }
} {
"Children": {
"1": {
"Child1": {
"A": "123"
},
"Child2": {
"B": "456"
}
},
"2": {
"Child1": {
"A": "123"
},
"Child2": {
"B": "456"
}
}
}
} Currently all Children's values are (null, null). Is it possible to bind the Parent class so that the dictionary values are not null? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Binding a configuration to a type supports (public) properties but unfortunately not fields. And value tuples have fields but no properties. Hence why the configuration binder cannot populate the value tuple Therefore, given the current feature set of Microsoft.Extensions.Configuration.Binder, the probably simplest solution to your problem is to replace the value tuple types involved in configuration binding with records/classes/structs featuring public properties. |
Beta Was this translation helpful? Give feedback.
Binding a configuration to a type supports (public) properties but unfortunately not fields. And value tuples have fields but no properties. Hence why the configuration binder cannot populate the value tuple
(Child1 Child1, Child2 Child2)
, because the tuple members Child1 and Child2 are fields. :-(Therefore, given the current feature set of Microsoft.Extensions.Configuration.Binder, the probably simplest solution to your problem is to replace the value tuple types involved in configuration binding with records/classes/structs featuring public properties.