Configuration Providers in .NET

C# CONCEPTS

Configuration in .NET is achievable with various configuration providers.

There are different types of providers that rely on many configuration sources. The article details each of the configuration provider’s variants and their corresponding sources.

  1. File configuration provider

  2. Environment variable configuration provider

  3. Command-line configuration provider

  4. Key-per-file configuration provider

  5. Memory configuration provider

Why is the configuration required?

Configuration in .NET is the capability to bind values to instances of .NET objects.

For example, the JSON provider can be utilized to map appsettings.json files to .NET objects with dependency injection. It enables the options pattern, i.e. classes to provide strongly typed access to collections of similar settings.

File configuration provider

FileConfigurationProvider is the base class for packing configuration from the file. The following providers derive from FileConfigurationProvider:

  1. JSON configuration provider

  2. XML configuration provider

  3. INI configuration provider

JSON configuration provider

The JsonConfigurationProvider class loads key-value from a JSON file. Install the Microsoft.Extensions.Configuration.Json NuGet package.

Overloads can be specified:

  1. If the file is optional

  2. Whether the configuration will be reloaded if the file changes

Consider the following code:

https://gist.github.com/ssukhpinder/6ff8c4fbd7547dcd43b32136ad2c8b65

The earlier code:

  1. Clears all existing key-value pairs providers by default added in the CreateDefaultBuilder(String[]) function inside Program.cs file.

  2. Sets the JSON configuration provider to load the appsettings.json and appsettings.Environment.json files with the following options:

  3. optional: true: The file is optional.

  4. reloadOnChange: true : Reloaded when file changes are saved.

XML configuration provider

The XmlConfigurationProvider class loads key-value pairs from an XML file at runtime. Install the Microsoft.Extensions.Configuration.Xml NuGet package.

The following snippet demonstrates the configuration of XML files using the XML configuration provider inside Program.cs file.

https://gist.github.com/ssukhpinder/55221df380ecf679846a5918f61050a1

The above code:

  1. Clears all existing key-value pairs by default added in the CreateDefaultBuilder(String[]) function inside Program.cs file.

  2. Build the XML provider to load the appsettings.xml and repeating-example.xml files with the following options:

  3. optional: true: The file is optional.

  4. reloadOnChange: true : Reloaded when any file changes are done.

  5. Build the command-line configuration provider if the given args contains arguments.

INI configuration provider

The IniConfigurationProvider class loads key-value pairs from an INI file at runtime. Install the Microsoft.Extensions.Configuration.Ini NuGet package.

The following code snippet clears all the configuration providers and adds the IniConfigurationProvider with two INI files as the source:

https://gist.github.com/ssukhpinder/80eb3cfccc19320ae7fff5bfec82f4b1

Environment variable configuration provider

The EnvironmentVariablesConfigurationProvider builds configuration from environment variable key-value pairs after reading appsettings.json, appsettings.Environment.json, and Secret manager.

Therefore, key-value pairs from the environment override values read from appsettings.json, appsettings.Environment.json, and Secret manager.

The following set commands:

  1. Set the environment keys-values of the preceding example on Windows.

  2. Test the settings by changing them from their default values. The dotnet run command must be run in the project directory.

set SecretKey="Secret key from environment"
set TransientFaultHandlingOptions__Enabled="true"
set TransientFaultHandlingOptions__AutoRetryDelay="00:00:13"
dotnet run

The above environment settings:

  1. Are only set in the current command line session. In other words, these settings are not accessible from another command prompt window.

  2. Web applications launched from the Visual Studio cannot access the settings.

Command-line configuration provider

Using the default configuration, the CommandLineConfigurationProvider load’s configuration from command-line argument key-value pairs after the following configuration sources:

  1. appsettings.json and appsettings.Environment.json files.

  2. Secret Manager in the Dev environment.

  3. Environment variables in windows.

Configuration key-value pairs set on the command line override values set with all the other configuration providers by default.

Command-line arguments

The following command sets keys-values using =:

dotnet run SecretKey="Secret key from command line"

The following command sets keys-values using. /:

dotnet run /SecretKey "Secret key set from forward slash"

The following command sets keys-values using. --:

dotnet run --SecretKey "Secret key set from double hyphen"

The key-value:

  1. The key must have a prefix of = or -- or / when the value follows a space.

  2. Isn’t required if = is used. For example, SomeKey=.

Key-per-file configuration provider

The KeyPerFileConfiguration provider uses a file directory as a configuration for key-value pairs.

The key is the file name. The value is the file’s contents.

To activate the key-per-file configuration, call the AddKeyPerFile extension method on an instance of ConfigurationBuilder. The directoryPath to the files must be an absolute path.

The double-underscore (__) is used as a key delimiter in file names.

.ConfigureAppConfiguration((_, configuration) =>
{
    var path = Path.Combine(
        Directory.GetCurrentDirectory(), "path/to/files");
configuration.AddKeyPerFile(directoryPath: path, optional: true);
})

Memory configuration provider

The MemoryConfiguration provider uses memory collection as a store for key-value pairs.

The following code snippet adds a memory collection to the configuration system:

https://gist.github.com/ssukhpinder/7ebd62d114be2d3a489dd10afd5e8228

One can choose from any of the configuration providers listed above but most commonly used are Json file provider and environment secrets provider.

Thank you for reading. I hope you like the article..!!

#Aspnetcore #Aspnet #Csharp #DotnetCore #Dotnet

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w