Building a .NET Core Configuration Source

As I've been teaching ASP.NET Core for a while now, some things I've been saying I've taken on faith. One of these was that building a Configuration Source (a provider that can read configuration and feed it into the configuration system) is fairly easy.

With a break in building my Vue course, I was curious so I decided to build a configuration source that I hope no one uses. It is a configuration source that reads the AppSettings in a web.config file. This is a thought exercise, not a recommendation.

Building the Configuration Source

In order to be a Configuration Source, you must derive from the IConfigurationSource interface. You could implement this interface directly, or if your configuration is file based (like the one I built), you can simply derive from FileConfigurationSource. This class deals with most of the problem of opening and reading a file. Since my Configuration Source is to read the web.config, that's perfect.

In my constructor, I just set some options that are really about how FileConfigurationSource handles a file:

The only thing I really need to do with the Source itself is to override the Build method and just return a new provider that does the actual work.

Building the Provider

The provider is where all the real work happens. Like the Configuration Source, there is an interface you can implement: IConfigurationProvider. For my needs, I am just going to use the FileConfigurationProvider as the base class as it goes well with the FileConfigurationSource:

With the implementation complete, we need to have a way to register it when we setup the configuration.

Adding Sources to Configuration

If you're just reading this to figure out how to use my provider, you can get it from Nuget, though I'd prefer you migrated your AppSettings to another configuration format. But if I can't talk you out of it, just add it to the project via the dotnet command-line:

> dotnet add package WilderMinds.Configuration.AppSettings

I could have required that you just add the source via the Add method:

This is awkward, so I think I'd prefer to create a convenient method to just call "AddAppSettings()" to make it easier. To do this, I just write an extension method for the IConfigurationBuilder so we can add it easily:

Ready to Learn Vue with ASP.NET Core?

Shawn's 4-hour course will get you up to speed in no time. Vue.js is a great middle-ground between React and Angular for people who don't like the complexity of Angular, and the overly componentized React. Learn today at Wilder Minds Training!