← Back to articles

ASP.NET Core managed config

Part of my ASP.NET Core recipe series: binding appsettings.json to typed config classes so settings are managed code instead of magic strings.

Tedd

Reading config is pretty straight forward task that most applications need. For many years I used Nini, which scratched that itch fairly well. With the advent of better libraries its not too difficult to deserialize your favorite formatted config file into a class.

With .Net Core we finally got some decent/easy to use config system built in by the help of the Options pattern. In short, reading config by deserializing sections of appsettings.json into DI-hosted objects.

Install

Install-Package Microsoft.Extensions.Options.ConfigurationExtensions

Implement

In Startup.cs ConfigureServices method:

services.Configure<AppSettings>(Configuration);
services.Configure<OneSectionSettings>(Configuration.GetSection("TheSection")); 

This would require a couple of classes, for example:

public class AppSettings
{
 public string RootValue { get; set; }
 public OneSectionSettings TheSection { get; set; }
}
public class OneSectionSettings
{
 public string SomeValue { get; set; }
} 

And a corresponding config section

"RootValue": "Yes, yes",
"OneSection": {
 "SomeValue": "Test"
} 

If config section/values do not exist it will not produce any error.

Using

public class HomeController : Controller
{
 private AppSettings _appSettings;

 public HomeController(IOptions<AppSettings> appSettings)
 {
 _appSettings = appSettings.Value;
 }
...
} 

Recall config object by IOptions and use its “Value” property to extract object.

Written by Tedd · Oslo, Norway

Updated 6 Feb 2020

Follow the journal via RSS