Setting up .NET Core Configuration Providers

Developer Support

In this blog post, Premier Developer Consultant Randy Patterson teaches us how to set up .NET Core configuration providers in Visual Studio. He shows how to look at NuGet packages to access the Configuration API and then setup the providers as ASP .NET Core web applications.


ASP Core uses the convenient Provider Pattern to load configuration key/value pairs from various sources and expose those to you as a single Configuration object. This allows you to grab a configuration key like ConnectionString with one line of code regardless of where it was sourced from. However, the configuration API is not available by default in .NET Core Console applications.

In this article we will look at the Nuget packages necessary to access the Configuration API and setup the same providers as ASP Core web applications.

Create a .NET Core Console Application

In Visual Studio 2017 go to .NET Core Then Console Application and give it a name like “MyCoreConsoleApp”

Next, add a JSON configuration file with the name of appsettings.json as the first source of configuration keys.

Be sure the property “Copy to Output Directory” is set to “Copy Always” for the newly added JSON file. This will ensure that the file is published with the application.

E:\SystemTemp\SNAGHTML198df66e.PNG

Replace the contents of the appsettings.json file with the following content:

{

"Message":"Hello from appsettings.json"

}

This will set the property “Message” to the value of “Hello……”

Write Some Code

Before we update the application, we need to add the Nuget package that contains the provider needed to load JSON configuration files.

install-package Microsoft.Extensions.Configuration.Json

Next, replace the contents of the Main method with the following code.

static void Main(string[] args)

{

IConfiguration config = new ConfigurationBuilder()

.AddJsonFile("appsettings.json", optional:true, reloadOnChange:true)

.Build();

Console.WriteLine($"Contents of Message Property: {message}");

Console.ReadKey();

}

This will load the appsettings.json file into the configuration object extracting each property and value. In our case we have one property defined named Message set to the value of “Hello from appsettings.json”. The WriteLine method will display the value of the Message property to the console window.

Running the application yields the following output.

You’ve successfully loaded configuration data from an appsettings.json file.

Add Environment Variables

Next, add the Environment Variables Provider by installing the following Nuget Package

install-package Microsoft.Extensions.Configuration.EnvironmentVariables

and update the Main method to include the provider

IConfiguration config = new ConfigurationBuilder()

.AddJsonFile("appsettings.json", optional:true, reloadOnChange:true)

.AddEnvironmentVariables()

.Build();

This will load environments variables into the configuration object and is useful for cross-platform or container deployments. Furthermore, because Environment Variables are loaded after the appsettings.json file, any duplicate keys will replace the values from the appsettings.json file.

Next, add an environment variable named “Message” to override the Message property in appsettings.json from the Project Properties Page

Looking at the output displayed below you can see that the environment variables provider replaced the Message key that was initially set in the appsettings.json file with the contents of the environment variable.

Add Command Line Arguments

Finally, we’ll add the Command Line Arguments configuration provider. Similar to the previous providers, the first step is to install the proper Nuget package:

Install-Package Microsoft.Extensions.Configuration.CommandLine

Next, update the Main method to load the new provider.

IConfiguration config = new ConfigurationBuilder()

.AddJsonFile("appsettings.json", optional:true, reloadOnChange:true)

.AddEnvironmentVariables()

.AddCommandLine(args)

.Build();

Finally, update the project properties to add a command line argument to replace the Message property with the string “Hello from args”.

Run the application and the output should look like the following

The property “Message” was set three times. Once in appsettings.json file, then as an environment variable and finally as a command line argument. The last provider loaded wins any conflicts.

Conclusion

.NET Core added a powerful and flexible configuration API that is available by default in ASP Core application. Simply adding a few Nuget Packages to any .NET Core application will give you the same flexibility. The order the providers are added to the configuration builder is critical as the last loaded overrides any previous values. By applying the providers in the order specified in this article (Json, Environment Variables and Command Line Arguments) you will have a similar configuration environment found in ASP Core applications.

3 comments

Discussion is closed. Login to edit/delete existing comments.

  • Solomio Sisante 0

    Nice article. 😉
    For those who encountered an error with this line:

    Console.WriteLine($”Contents of Message Property: {message}”);

    I solved mine by adding 1 line of code above it so it looks like the code below:

    string message = config.GetValue(Type.GetType(“System.String”), “Message”).ToString();
    Console.WriteLine($”Contents of Message Property: {message}”);

    Cheers!

  • Jan Andersen 0

    I had to add:
    string message = config.GetSection(“Message”).Value.ToString();
    before:
    Console.WriteLine($”Contents of Message Property: {message}”);

    /Jan

    • Cesar Gonzalez 0

      I used:
      IConfiguration Config = new ConfigurationBuilder()
      .SetBasePath(“c:\\Users\\myname\\Documents\\workspace\\MyProject”)
      .AddJsonFile(“appsettings.json”, optional: true, reloadOnChange: true)
      .Build();

      string message = Config[“Message”];
      Console.WriteLine($”Contents of Message Property:{message}”);

Feedback usabilla icon