ASP.NET 5 Configuration – Settings Classes

In earlier Configuration examples, we used IConfigurationRoot to access settings with a string key, which returned a string value.  In the following example, we’ll see how to configure typed access to settings. The code snippets shown here are from the command line example project. You can find both the command line project and a Visual Studio 2015 project here:

We will use this appsettings.json file:

We create the following classes to use for settings.  Note that the MySettings class does not include a property for "otherSettings", and we have a class, OtherSettings for only that section of the settings.

In the project.json file, we add a dependency on Microsoft.Extensions.OptionsModel:

Then, in the Startup class, we add a ConfigureServices method, call the AddOptions extension method, which registers services that allow us to use settings classes, and configure our settings classes (note how we use GetSection to load a sub-section of settings):

To access settings, we rely on dependency injection to provide an IOptions<T>, which we will use to get an instance of the settings class T.  For example, the MyClass constructor takes an IOptions<OtherSettings> argument and we use the Value property to get an OtherSettings instance:

Typically, we will need access to settings in the Startup.Configure method.  Again, we rely on dependency injection to provide an IOptions<T>.  Here we also take an instance of MyClass, which we registered in ConfigureServices:

Running the application and browsing to it, we see the expected settings values displayed:

settings-classes-output

Voilà! With very little effort we have typed access to settings, and, if the editing environment supports it, code hints as well!

Leave a Reply