bungeemonkee / Configgy

A simple, powerful, extensible, testable .NET configuration library.
MIT License
41 stars 4 forks source link

Problem Reading in Array of String #36

Closed kenpfalk closed 1 year ago

kenpfalk commented 1 year ago

Put this in json file

"Dogs": [ "St. Bernard"]

Tried these in Config

List<string> Dogs { get; set; }

string[] Dogs { get; set; }

public IEnumerable<string> Dogs { get; set; } = null!;

[Configgy.Coercion.CsvCoercerAttribute(typeof(string))] public string[] Dogs { get; set; }

but all error out

bungeemonkee commented 1 year ago

I looked into this and it took me a while to remember why this is like this. The core issue is that the IConfigurationRoot is not just a lookup inside a JSON object (which presumably could allow getting the JSON of a sub-object fairly easily). It is a complex key-value system that allows multiple sources to be included in a priority order (not unlike a simplified Configgy with fewer features ;)). As a result it doesn't make sense to be able to extract values like this.

However, JOSN can be used to populate a complex object within a configuration using the JsonCoercerAttribute. But fort that to work the config key must return the JSON to be parsed as a string. So the solution looks like this:

Set the property in the config object to be a string array (or list of string) with the JsonCoercerAttribute on it like so:

[JsonCoercer]
public string[] Dogs { get; set; }

Then the value in the appsettings.json file needs to be set as an escaped JSON string inside the JSON configuration object like this:

{
    "Dogs" : "[ \"St. Bernard\" ]"
}

Which isn't ideal but it works and allows all the expected Configgy behavior.

It is also possible to write a customized version of ConfigurationRootSource that can pull in the configuration section and all keys/values within it in a recursive way then serialize that into a JSON string that can be returned as the resulting configuration value. But this is extremely complex for a use case that I do not believe is particularly common. IMHO this functionality should not be part of the core Configgy library.