Packaging Configuration Data into Classes

In this lesson, we will learn how to organize configuration data into classes that will be available through dependency injection.

It is not desirable that various application parts access the whole configuration as this may create hidden dependencies between application subparts. For instance, a controller might use a pager setting that was conceived for another section of the website, so changing the configuration for that section might unexpectedly change the behavior of other application sections as well.

Configuration sections help to organize data, but we need a way to inject data from a single section preventing access to other sections. It is best to have controllers and views receive data already converted into C# types so they don’t have to convert from strings. The ASP.NET Core options framework solves this problem.

The ASP.NET Core options framework solves this problem.

ASP.NET Core options framework

Thanks to the ASP.NET Core options framework, configuration data from a section can be deserialized into C# options classes that are available in the dependency injection engine. This way, controllers and views can receive these classes instead of the whole configuration. This resolves the issue of converting data from the string format and receive the data needed.

Preparing options classes is quite easy, it is just extracting the needed sections and declaring the classes they must fill. This job is done in the ConfigureServices method of Startup.cs, as shown below:

services.Configure<EmailConfig>(Configuration.GetSection("Email"));

The definition for stored email account configuration:

Get hands-on with 1400+ tech skills courses.