One of the things that is very different when you move to Asp.Net Core is the way that configuration files are treated. This partly comes from the drive to move things that are not configuration out of configuration files. It looks like the days of app.config and web.config are numbered and, in their place, we have AppSettings.Json. Here’s an example of what that new file might look like:
The old files were very flat and, using the configuration manager, you could simply read a setting; something like this:
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key];
So, the first question is: can you still do this? The answer is, pretty much, yes:
public void ConfigureServices(IServiceCollection services)
IConfigurationBuilder builder = new ConfigurationBuilder()
Configuration = builder.Build();
However, you now have the option of creating a class to represent your settings; something like:
AzureAppSettings azureAppSettings = new AzureAppSettings();
If you use this approach then you’ll need an extension library from NuGet:
Is it better, or worse?
At first glance, it would appear that things have gotten worse; or at least, more complex. However, the previous method had one massive problem: it was a static class. The result being that most people have written their own wrapper around the ConfigurationManager class. We now have a class that can be injected out of the box; alternatively, you can split your configuration up into classes, and pass the classes around; the more I think about this, the better I like it: it makes more sense to have a class or method accept parameters that are necessary for its execution and, arguably, breaks the single responsibility principle if you’re faffing around trying to work out if you have all the operating parameters.
The other advantage here is that the configuration file can now be hierarchical. If you have well designed, small pieces of software then this might not seem like much of an advantage, but if you have 150 settings in your web.config, it makes all the difference.