'How can I load an empty object into a dictionary from appsettings.json?
I'm trying to load values into a custom options class on app startup in C#/.net6. Some of the input from appsettings.json is not being loaded as I would like.
My options class looks like this:
public class CustomOptions
{
public Dictionary<string, CustomInfo> MyOptions { get; set; }
}
public class CustomInfo
{
public Dictionary<string, string> DictionaryField { get; set; } = new Dictionary<string, string>();
public List<string> ListField { get; set; } = new List<string>();
}
and appsettings.json contains the following:
"CustomOptions" : {
"MyOptions": {
"OptionOne": {},
"OptionTwo": {
"DictionaryField": {
"ValueOne": "somevalue",
"ValueTwo": "someothervalue"
},
"ListField": [
"ListItem"
]
}
}
}
and loading the options in Program.cs with
builder.Services.AddOptions<EndpointOptions>().Bind(builder.Configuration.GetSection(EndpointOptions.Key));
As it stands, OptionTwo is loaded correctly with all fields set, yet OptionOne does not even appear in the injected IOptions<TOptions> service.
What I would like is for OptionOne to be loaded into the MyOptions dict with a default CustomInfo object or null value. Is this possible?
Edit: I need to be able to add more options beyond OptionOne and OptionTwo at some point, and ideally would be able to do this through appsettings.json, hence the need for a dictionary in MyOptions class. All these options will still follow the CustomInfo class.
Solution 1:[1]
The JsonConfigurationFileParser ignores any empty object and simply add value of null as configuration value, that is ignored during binding.
If you really need both options to be added to the dictionary, you could add at least one property to OptionOne section:
"OptionOne": {
"DictionaryField": {}
}
Frankly, in the sense of low memory allocating, it makes sense to not create an empty instance of CustomInfo, but use the TryGetValue method on dictionary to test if the value exists.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | weichch |
