Strongly Typed Configuration Settings in ASP.NET Core Part II

Rick Strahl wrote an amazing post about getting strongly typed configuration objects in ASP.NET Core. The one gripe I have about the approach, by no fault of his, is the proliferation of the interface IOptions<T>. Seeing the abstraction in my code feels leaky. This post will show you how to take the strongly typed configuration and directly register it with the ServicesCollection in your ASP.NET Core applications.

The Alternative Solution

Let’s take a simple class, which will be hydrated via our strongly typed object. The passing of the BankSettings object is an optional step I decided to take. I pass the settings into the constructor as the Bank object will be a Singleton in my application and I don’t want anyone (especially me) accidentally setting the Bank properties.

publicstaticclassBankExtensions{publicstaticIServiceCollectionAddBank(thisIServiceCollectionservices,IConfigurationRootconfiguration){varsection=configuration.GetSection("Bank");// we first need to create an instancevarsettings=newBankSettings();// then we set the properties newConfigureFromConfigurationOptions<BankSettings>(section).Configure(settings);// then we register the instance into the services collectionservices.AddSingleton(newModels.Bank(settings));returnservices;}}

If you followed the post correctly, you should be able to inject the object into your application models without that pesky IOptions<T> interface.