Class to Read Values Stored in appsettings.json

The following class could come in handy if you want to values from the appsettings.json file present in ASP.NET Projects.  It uses an indexer to access the values in the file.

Say your appsettings.json file looks like this:

{
  "MyKey": "MyValue"
}

Access it by doing the following:

var value = AppSettings.Instance["MyKey"];

The code for the AppSettings class:

public sealed class AppSettings
{
    private static AppSettings _instance;

    IConfigurationRoot _configurationRoot;

    private AppSettings()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        _configurationRoot = builder.Build();
    }

    public static AppSettings Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new AppSettings();
            }
            return _instance;
        }
    }

    public string this[string key]
    {
        get
        {
            return _configurationRoot[key];
        }            
    }    
}