Using Memory Configuration Provider In .NET Applications

In one of my previous posts this month, I briefly wrote about the configuration providers. There are many different types of configuration providers. In this article, let’s have a look at one of them, the Memory configuration provider.

What is it ?

.NET has a special interface, IConfigurationProvider and a class ConfigurationProvider, which is for standardizing the APIs for reading configurations from different sources. This interface creates key-value pairs for the application.

The JSON, XML and INI file configuration providers implement this interface to generate key-value pairs from the configurations. Command line configuration provider reads the settings provided on the command line while invoking the application and converts them to key-value pairs format.

Similarly, there are other implementations too. In fact, you can create your own custom implementation of IConfigurationProvider interface.

In this article, we are going to have a specific configuration provider which allows to convert any in memory collection to configuration, the MemoryConfigurationProvider.

How to use it ?

Below code snippet shows how to user in-memory collection and apply it as a configuration so that those values are available via IConfiguration interface.

You can create .NET Core web application (MVC) and change the CreateHostBuilder method to use AddInMemoryCollection to apply the settings from in-memory collection (i.e. Dictionary<string, string>).

In order to use this configuration, you can use it like any other configuration settings, just inject IConfiguration object (Or IOptions if you Bind with a configuration section).

Where would we use it ?

In my opinion, this could be helpful in the scenarios where

  • the application reads data from some data source
  • then data is transformed to derive the configuration settings

Obviously there is another way to make it happen. You can also create the custom configuration provider. But in-memory configuration provider might be easy option to start with, without knowing additional internals about ConfigurationProvider class.

Let me know your thoughts about the uses cases for in-memory configuration provider.

Leave a Reply

This Post Has One Comment