I'm using dotnet core 6/7 and try to bind a list of Settings.
Imagine the following appsettings:
{
"parameters": [
null,
null,
{
"name": "test"
}
]
}
together with the following models:
public class ParameterDefinition : List<Parameter?> {}
public class Parameter {
public string Name { get; set; }
}
which are configured somewhere in the ConfigureServices-Section:
services.Configure<ParameterDefinition>(Configuration.GetSection("parameters"));
The ConfigurationProvider shows the correct entries like:
"parameters:0": "",
"parameters:1": "",
"parameters:2:name": "test"
When getting the configuration via dependency injection (IOptions<ParameterDefinition>) the ParameterDefinition only contains one element, but it should have three, were the first two of them are null.
How can I correctly get the List including the null-values?
As you pointed out, the
ConfigurationProviderholds all entries; thenullones have become an empty string. These somewhere get lost when being processed towards a settings class.To work around the issue:
Parameterclassas astruct.UPDATE: As from your comment on this post, this suffices to solve the issue.
Below steps 2 and 3 are optional. Leaving these here for future reference, in case someones settings model looks similar.
ParameterDefinitionclass from being/inheriting aList<T>to aclasshaving an array (orList<T>) property of typeParameter?.IOptions<ParameterDefinition>as below. The json structure can stay as-is.Since you don't have a
"ParameterDefinition"element/section in your json setup, an empty string is passed toBindConfiguration.Alternatively, you can call the
Configuremethod that you are already using, but that does require an additionalParameterDefinitionjson wrapper element/section.Now when an
IOptions<ParameterDefinition>instance gets injected, it will hold 3 items; 1Parameterinstance and 2nullvalues.