Configuration in .NET

Configuration in .NET is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources:

  • Settings files, such as appsettings.json
  • Environment variables
  • Azure Key Vault
  • Azure App Configuration
  • Command-line arguments
  • Custom providers, installed or created
  • Directory files
  • In-memory .NET objects
  • Third-party providers

Configure console apps

New .NET console applications created using dotnet new or Visual Studio by default do not expose configuration capabilities. To add configuration in a new .NET console application, add a package reference to Microsoft.Extensions.Hosting. Modify the Program.cs file to match the following code:

using Microsoft.Extensions.Hosting;

using IHost host = Host.CreateDefaultBuilder(args).Build();

// Application code should start here.

await host.RunAsync();

The Host.CreateDefaultBuilder(String[]) method provides default configuration for the app in the following order:

  1. ChainedConfigurationProvider : Adds an existing IConfiguration as a source.
  2. appsettings.json using the JSON configuration provider.
  3. appsettings.Environment.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  4. App secrets when the app runs in the Development environment.
  5. Environment variables using the Environment Variables configuration provider.
  6. Command-line arguments using the Command-line configuration provider.

Configuration providers that are added later override previous key settings. For example, if SomeKey is set in both appsettings.json and the environment, the environment value is used. Using the default configuration providers, the Command-line configuration provider overrides all other providers.

Binding

One of the key advantages of using the .NET configuration abstractions is the ability to bind configuration values to instances of .NET objects. For example, the JSON configuration provider can be used to map appsettings.json files to .NET objects and is used with dependency injection. This enables the options pattern, which uses classes to provide strongly typed access to groups of related settings. .NET configuration provides various abstractions. Consider the following interfaces:

These abstractions are agnostic to their underlying configuration provider (IConfigurationProvider). In other words, you can use an IConfiguration instance to access any configuration value from multiple providers.

Basic example

To access configuration values in their basic form, without the assistance of the generic host approach, use the ConfigurationBuilder directly.

Tip

The System.Configuration.ConfigurationBuilder is different than the Microsoft.Extensions.Configuration.ConfigurationBuilder. All of this content is specific to the Microsoft.Extensions.* NuGet packages and namespaces.

Consider the following C# project:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>true</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" />
  </ItemGroup>

</Project>

The preceding project file references several configuration NuGet packages:

Consider an example appsettings.json file:

{
    "Settings": {
        "KeyOne": 1,
        "KeyTwo": true,
        "KeyThree": {
            "Message": "Oh, that's nice..."
        }
    }
}

Now, given this JSON file here is an example consumption pattern using the configuration builder directly:

using Microsoft.Extensions.Configuration;

// Build a config object, using env vars and JSON providers.
IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddEnvironmentVariables()
    .Build();

// Get values from the config given their key and their target type.
Settings settings = config.GetRequiredSection("Settings").Get<Settings>();

// Write the values to the console.
Console.WriteLine($"KeyOne = {settings.KeyOne}");
Console.WriteLine($"KeyTwo = {settings.KeyTwo}");
Console.WriteLine($"KeyThree:Message = {settings.KeyThree.Message}");

// Application code which might rely on the config could start here.

// This will output the following:
//   KeyOne = 1
//   KeyTwo = True
//   KeyThree:Message = Oh, that's nice...

The preceding C# code:

  • Instantiates a ConfigurationBuilder.
  • Adds the "appsettings.json" file to be recognized by the JSON configuration provider.
  • Adds environment variables as being recognized by the Environment Variable configuration provider.
  • The config instance is used to get the required "Settings" section and get the corresponding Settings instance.

The Settings object is shaped as follows:

public class Settings
{
    public int KeyOne { get; set; }
    public bool KeyTwo { get; set; }
    public NestedSettings KeyThree { get; set; } = null!;
}
public class NestedSettings
{
    public string Message { get; set; } = null!;
}

Basic example with hosting

To access the IConfiguration value, you can rely again on the Microsoft.Extensions.Hosting NuGet package. Create a new console application, and paste the following project file contents into it:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>true</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
  </ItemGroup>

</Project>

The preceding project file defines:

  • That the application is an executable.
  • That an appsettings.json file is to be copied to the output directory when the project is compiled.
  • That the Microsoft.Extensions.Hosting NuGet package reference is added.

Add the appsettings.json file at the root of the project with the following contents:

{
    "KeyOne": 1,
    "KeyTwo": true,
    "KeyThree": {
        "Message": "Thanks for checking this out!"
    }
}

Replace the contents of the Program.cs file with the following C# code:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using IHost host = Host.CreateDefaultBuilder(args).Build();

// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

// Get values from the config given their key and their target type.
int keyOneValue = config.GetValue<int>("KeyOne");
bool keyTwoValue = config.GetValue<bool>("KeyTwo");
string keyThreeNestedValue = config.GetValue<string>("KeyThree:Message");

// Write the values to the console.
Console.WriteLine($"KeyOne = {keyOneValue}");
Console.WriteLine($"KeyTwo = {keyTwoValue}");
Console.WriteLine($"KeyThree:Message = {keyThreeNestedValue}");

// Application code which might rely on the config could start here.

await host.RunAsync();

// This will output the following:
//   KeyOne = 1
//   KeyTwo = True
//   KeyThree:Message = Thanks for checking this out!

When you run this application, the Host.CreateDefaultBuilder defines the behavior to discover the JSON configuration and expose it through the IConfiguration instance. From the host instance, you can ask the service provider for the IConfiguration instance and then ask it for values.

Tip

Using the raw IConfiguration instance in this way, while convenient, doesn't scale very well. When applications grow in complexity, and their corresponding configurations become more complex, we recommend that you use the options pattern as an alternative.

Configuration providers

The following table shows the configuration providers available to .NET Core apps.

Provider Provides configuration from
Azure App configuration provider Azure App Configuration
Azure Key Vault configuration provider Azure Key Vault
Command-line configuration provider Command-line parameters
Custom configuration provider Custom source
Environment Variables configuration provider Environment variables
File configuration provider JSON, XML, and INI files
Key-per-file configuration provider Directory files
Memory configuration provider In-memory collections
App secrets (Secret Manager) File in the user profile directory

For more information on various configuration providers, see Configuration providers in .NET.

See also