I've been working with Sitecore CMS for the past few years and now I'm back to “pure” ASP.Net MVC development. I like the way Sitecore CMS handles configuration files
Here all logical parts of the configuration are put into separate (small) configuration files, all files are merged at application startup, and patches are applied when attaching files. To my taste, this is a clean and clear solution.
Back to pure ASP.Net MVC core - you can add files to the config one by one. All the others will be merged into the final config. And this seems fine until you develop an application with extensive customization capabilities (like a CMS) and have hundreds of configuration files.
There are 3 types of configuration files that you can add to ASP.Net Core out of the box: .json, .xml и
Let's create extension methods for IConfigurationBuilder that allow you to include multiple configuration files of these types with a single line of code in Program.cs..ini
.
The basic idea is to get a list of the necessary files (by searching the directory) and add them all to the IConfigurationBuilder by using the necessary standard methods in a loop.
The logic will be roughly the same for each extension, the only difference is the method called by the linker.
- Let's start by creating a public static class ConfigurationExtensions (of course, any name will do). The class can be created in any project of your solution. In case it is not an ASP.Net Core project type, you may need to install additional nuget packages for publicly available methods such as Microsoft.Extensions.Configuration.Json, etc.
- Re-use the GetAvailableFiles() method.
- Add a delegate to carry the “single file” methods of IConfigurationBuilder ( AddConfigFileDelegate )
4. Connect the general logic for adding files to IConfigurationBuilder ( AddConfigFiles() method )
5. Add public methods to extend the functionality of IConfigurationBuilder - AddJsonFiles, AddXmlFiles and AddIniFiles.filenamePattern by default
This allows us to use the extension in the following way:
All files will be added in alphabetical order. You are also allowed to filter files in directories not only by extension.
The full source code is presented below: