I'm storing some IConfiguration as json in my sqlserver db so I can then bind them to some already constructed classes in order to provide dynamic settings.
At some point I might change the binded properties new at runtime and then update the db. The thing is that when i need to, the class might have more properties that aren't supposed to be bound and shouln't be serialized. I am therefore keeping the IConfiguration as a property of my class. Another reason why I'm using this approach is that I need to istantiate other children classes from the class that has loaded the configs, and save them to db when i do.
The thing is that when I serialize an IConfiguration i only get an empty json string like "{}". I suppose i could do some shenanigans leveraging .AsEnumerable() but isn't there a better way?
My sample code would look somewhat like this
public class ConfigurableClass
{
public int ChildrenCount { get; set; } = 1069;
public bool IsFast { get; set; } = false;
public bool HasChildren { get; set; } = false;
public int Id { get; }
public ConfigurableClass(int id) { Id = id; }
}
static void Main(string[] args)
{
IEnumerable<string> configs = SqlConfigLoader.LoadConfig();
foreach (var str in configs)
{
Console.WriteLine("Parsing new Config:");
var builder = new ConfigurationBuilder();
IConfiguration cfg = builder.AddJsonStream(new MemoryStream(Encoding.Default.GetBytes(str)))
.Build();
var stepExample = new ConfigurableClass(9);
cfg.Bind(stepExample);
//do work with the class that might change the value of binded properties
var updatedCfg = cfg;
Console.WriteLine(JsonSerializer.Serialize(updatedCfg));
Console.WriteLine();
}
Console.ReadLine();
}
Edit
I Also tried a diffent approach, by converting the IConfiguration to a nested dictionary like this
ublic static class IConfigurationExtensions
{
public static Dictionary<string,object> ToNestedDicionary(this IConfiguration configuration)
{
var result = new Dictionary<string, object>();
var children = configuration.GetChildren();
if (children.Any())
foreach (var child in children)
result.Add(child.Key, child.ToNestedDicionary());
else
if(configuration is IConfigurationSection section)
result.Add(section.Key, section.Get(typeof(object)));
return result;
}
}
But I lose the implicit type behind a given JsonElement:
if i serialize the resulting dictionary i get thing like "Property": "True" instead of "Property" : true