Using Web.Config (or App.Config) XML files to store and retrieve settings for an application, imho, has always been a bit of a pain. Unless we write quite a bit of custom code, all we really get is a property bag of stings for our custom (user) configurations.
.NET Core uses, primarily, JSON files for configuration. Gone is the old ConfigurationManager that would let you pull settings from you web.config on the fly. I think this is a good thing. Instead, in our startup, we, again, can use DI. Basically, an object is serialized from our JSON config, and where we need it, we inject it via the IOptions interface.
The effect here is two fold. The first is being able to use simple strongly typed objects to retrieve our configuration and the second is that now we can use proper depdency injection for those objects. Well, really, a third side effect is also that we no longer have a reliance on System.Web.
Basically, an object is serialized from our JSON config, and where we need it, we inject it via the IOptions interface.
Imagine that we create a node in our appsettings.json called “AppSettings” (very original, I know):
"AppSettings": { "IsQueueTabEnabled": true, "IsSearchTabEnabled": true, "IsAdminTabEnabled": true, "IsManageCampaignsEnabled": true, "IsManageUsersEnabled": true, "IsManageQuestionsEnabled": true, "MaxSearchPages": 50 }
Then, we create a correpsonding class:
public class AppSettings { public bool IsQueueTabEnabled { get; set; } public bool IsSearchTabEnabled { get; set; } public bool IsAdminTabEnabled { get; set; } public bool IsManageCampaignsEnabled { get; set; } public bool IsManageUsersEnabled { get; set; } public bool IsManageQuestionsEnabled { get; set; } public int MaxSearchPages{ get; set; } }
In the StartUp.cs’s ConfigureServices method, then we need to configure the class/object:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
With that bit of configuration, now, wherever we need “AppSettings,” we inject it as a typed instance of IOptions. If I need, for example, this settings in a domain class, it would look like this:
private AppSettings _appSettings; public class MyHelper(IOptions<AppSettings> options) { _appSettings = options.Value; }
One other point of note is that, unlike older .NET using a Web.Config, your strongly typed objects are, effectively, singletons that do not get refreshed automatically. .NET Core provides a few other interfaces that can manage runtime changes which I’m still looking at.