[SOLVED] Optimal way to store objects in AppConfig.json

Issue

My AppConfig.json:

{
     "MyTimeZone: "CET",
     "RegularString" : "SomeValue",
     "AnArray" : ["1","2"]
}

My POCO class:

public class Settings
{
     public TimeZoneInfo MyTimeZone { get; set; }
     public string RegularString { get; set; }
     public IList<string> AnArray { get; set; }
}

Registry.cs:

var configuration = GetConfiguration("AppSettings.json");
services.Configure<Settings>(configuration.GetSection("Settings"));

This of course does not bind "CET" into a valid TimeZoneInfo object. Now the question is what is the best place in my application (a web app) to convert from string to TimeZoneInfo? Is there a way to automatically convert string config values to objects based on certain rules without creating custom converters?

Solution

Reference Use DI services to configure options

services.AddOptions<Settings>()
    .Configure<IConfiguration>((setting, configuration) => {
        var section = config.GetSection("Settings");
        //This will populate the other properties that can bind by default
        section.Bind(setting);

        //this will extract the remaining value and set it mnually
        string value = section.GetValue<string>("MyTimeZone");
        TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(value);
        setting.MyTimeZone = info;
    });

The complex setting value can be extracted directly from configuration via DI and used to create the time zone and apply it to the settings.

Answered By – Nkosi

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *