This tip reveals a very simple way to read sections of a web application's config file as objects, without requiring the Options pattern or dependency injection.
In ASP.NET Core, it's quite easy to configure a a group of related settings in the config file, normally appsettings.json, to be deserialized as classes and injected into DI clients. It is, however, apparently not as simple to simply deserailize an object from this file and use it before the DI container has been fully initialized.
Using the Code
As an example, I have taken code of mine where I configure password rules for ASP.NET Identity by reading these rules as an object from appsettings.json. Normally, I would hard code these settings, as they seldom change during the lifetime of an application, but in a project where I'm including password generation, and I want generated passwords to conform to the same rules as those configured for Identity, I thought it would be nice to store these password options in appsettings.json.
This is how I store the password rules in the config file:
And this is how I read these settings and configure
Identity, in Startup.cs:
var pwdSection = Configuration.GetSection("Authentication:PasswordRules");
var pwdOpts = pwdSection.Get<PasswordOptions>();
options.Password = pwdOpts;
options.Password property of the
IdentityOptions being configured is a simple object of class
PasswordOptions. All I have to do is make sure the "
Authentication:PasswordRules" section of my config file is a serialization of an object.
The magic happens with the call:
var pwdOpts = pwdSection.Get<PasswordOptions>()
This would not normally be possible, unless I include the following NuGet package in the project.
This was kindly revealed by this StackOverflow answer.
This is the first version of this tip.