Configuration with .NET Core

.NET Core gives more and easier options for configuration. Do you store your configuration values with XML files? Do you use XML transformations for different configuration values depending on the application runs on the production, staging, or development server? .NET Core has different ideas here. This article shows how to use Microsoft.Extensions.Configuration for configuration files.

F1 Steering Wheel

Using Simple Configuration

The first code snippet setups configuration to read it from the JSON file appsettings.json. The NuGet package Microsoft.Extensions.Configuration is needed for all the configuration types, such as the ConfigurationBuilder. To read the configuration file from JSON, another NuGet package, Microsoft.Extensions.Configuration.Json is required. Creating a new ConfigurationBuilder instance, a Fluent API is offered. The SetBasePath method defines the directory where the configuration files are read from there on. The AddJsonFile extension method that has been made available from the Microsoft.Extensions.Configuration.Json package defines the filename for the configuration file. After this filename is configured, the Build method is invoked which returns an IConfigurationRoot object. This returned object is assigned to the Config property which allows accessing the configuration values later on.

private static void SetupSimpleConfiguration()
{
    Config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();  
}

public static IConfigurationRoot Config { get; private set; }

SetBasePath needs to be invoked before the AddJsonFile method – to define the base path where the configuration files are read from now on. You can use multiple configuration files from different paths where you just need to specify the base path again.

The configuration file applicationsettings.json defines a simple configuration value for the key SimpleConfig.

{
  "SimpleConfig": "SimpleValue"
}

To read the configuration value, all what’s needed is to use the indexer of the IConfigurationRoot and pass the name of the key:

private static void ReadSimpleConfiguration()
{
    Console.WriteLine(nameof(ReadSimpleConfiguration));
    string val1 = Config["SimpleConfig"];
    Console.WriteLine($"Read {val1} using the key SimpleConfig");
    Console.WriteLine();
}

The variable val1 now contains the string SimpleValue.

Using Different Configuration Providers

There’s no need to store your configuration values within JSON files. You can use XML files, also can make use of INI files, pass configuration files with command line arguments, or environmental variables – you can use any provider for configuration values, or create your own. To use configuration files from XML files, the NuGet package Microsoft.Extensions.Configuration.Xml can be used, with environmental variables the package Microsoft.Extensions.Configuration.EnvironmentVariables.

private static void SetupConfigurationWithMultipleProviders(string[] args)
{
    Config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .AddCommandLine(args)
        .Build();
}

To run the application from Visual Studio, the program arguments as well as the environmental variables can be set from the Debug settings of the project properties:

Visual Studio Debug Settings

Using the same configuration keys with multiple providers, the order how the providers are added to the ConfigurationBuilder becomes important. The provider that is added last wins.

Defining Different Values for Development, Staging, Production

With the new configuration it is easy to supply different configuration values for development, staging, and production environments. With the sample project I’ve configured the environment variable Environment to the name of the environment, e.g. Staging. This environmental variable is used to define the filename for the configuration. appsettings.json is used for the configuration that is not different with the servers, with the development server the additional configuration file appsettings.development.json is used, with the production server appsettings.production.json. By default, if the file does not exist, an exception is thrown. Passing true with the second argument of AddJsonFile, it can be specified that the setting is optional.

private static void SetupConfigurationWithOptionalSettings()
{
    string environment = Environment.GetEnvironmentVariable("Environment");

    Config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{environment}.json", optional: true)
        .Build();
}

Reading From Sections

With the previous sample, no hierarchy was used. With JSON files it is also possible to define hierarchical levels. For example, the following JSON file defines a section ConnectionStrings, and the connection named DefaultConnection below it.

{
  "ConnectionStrings": {
    "DefaultConnection": "Connection string to the staging database"
  }
}

To read the connection string, the GetSection method can be used passing the section name. The GetSection method returns an IConfigurationSection where in turn again the indexer can be used to retrieve the values within this section.
For easier use of connection strings, the extension method GetConnectionString exists that does the same – retrieving a key from the section ConnectionStrings.

private static void ReadConfigurationWithOptionalSettings()
{
    Console.WriteLine(nameof(ReadConfigurationWithOptionalSettings));
    Console.WriteLine(Config.GetSection("ConnectionStrings")["DefaultConnection"]);
    Console.WriteLine(Config.GetConnectionString("DefaultConnection"));
    Console.WriteLine();
}

Summary

Microsoft.Extensions.Configuration. offers new configuration options with .NET Core. You can use this new environment not only with ASP.NET Core, but also with existing applications using the .NET Framework. The new configuration offers reading configuration values from different sources where providers are available, such as JSON, XML, INI files, but also environmental variables and program arguments.

Sample code is available with the More Samples from my book Professional C# 6 and .NET Core 1.0.

In future blog posts I’ll show how to manage user secrets with the configuration, and configure dependency injection services with Microsoft.Extensions.Configuration.

Have fun with programming and learning!
Christian

More Information

More information about the .NET Core configuration is available in my new book and my workshops.

Professional C# 6 and .NET Core 1.0

Trainings

Related Information

What is .NET Core?

dotnet-new

Dependency Injection with .NET Core

Steering wheel image © Franky242 | Dreamstime.com Steering Wheel Of Mercedes Formula 1 Car

Advertisement

8 thoughts on “Configuration with .NET Core

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.