Search code examples
c#asp.net-core.net-coreasp.net-core-mvcasp.net-core-webapi

Getting an appsettings.json config value inside Program.cs with type safety


At the moment I'm using the code below in Program.cs to read a value from the appsettings.json file.What concerns me is that if I rename the section or the property (TimeOutInSeconds) to something else the code will compile fine but there will be a runtime error:

var timeoutInSeconds = configuration.GetSection("FluentApiSettings").GetValue<int>("TimeOutInSeconds");

Is there anyway I can access the settings in a strongly typed way by casting to a FluentApiSettings class?


Solution

  • You can use ConfigurationBinder.Bind for this:

    FluentApiSettings.cs:

    public class FluentApiSettings
    {
        public int TimeOutInSeconds { get; set; }
    }
    

    Program.cs:

    var fluentApiSettings = new FluentApiSettings();
    configuration.GetSection("FluentApiSettings").Bind(fluentApiSettings);
    

    You can also make that a little simpler with ConfigurationBinder.Get, which creates the instance for you too:

    Program.cs:

    var fluentApiSettings = configuration.GetSection("FluentApiSettings")
        .Get<FluentApiSettings>();