Post

Add a JSON configuration file to a .NET Core console application

A .NET Core application can handle configuration using different formats (providers) like memory, command line and environment. Here, we will be using a file provider, more specifically, a JsonConfigurationProvider. Click here to learn more about the different types of configuration providers.

Project Setup

We will start by creating a console application and adding the NuGet package for the provider. In our case, it will be a JSON provider.

1
2
3
$ dotnet new console -o sample-configuration -n SamepleConfiguration
$ cd SampleConfiguration
$ dotnet add package Microsoft.Extensions.Configuration.Json

Let’s also add an appsettings.json file that we can use for testing.

1
2
3
4
5
6
7
8
9
{
  "ConnectionStrings": {
    "Sample": "Server=(localdb)\\mssqllocaldb;Database=Sample;Trusted_Connection=True;"
  },
  "TheSettings": {
    "IsEnabled": true,
    "Delay": "00:01:00"
  }
}

Not required, but you might want to add CopyToOutputDirectory in your project file.

1
2
3
4
5
6
7
8
9
10
11
<Project Sdk="Microsoft.NET.Sdk">

	...

  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

Configuration

We can now add some code for our sample application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace SamepleConfiguration
{
    class Program
    {
        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                .AddJsonFile("appsettings.json", optional: false)
                .Build();
        }
    }
}

The Build() method returns a new instance of ConfigurationRoot. We can already use that to retrieve information from our configuration file. For example, we could get the connection string using only its key.

1
2
var connectionString = configuration.GetConnectionString("Sample");
Console.WriteLine(connectionString);

We could do the same to access other configurations, but there is a better way. Let’s create a class that will map our configuration section.

1
2
3
4
5
class MySettings
{
    public bool IsEnabled { get; set; }
    public TimeSpan Delay { get; set; }
}

In order to be able to do that, we need to add another NuGet package.

1
> dotnet add package Microsoft.Extensions.Configuration.Binder

This package provides a .Bind() extension method that can map a section of our configuration file into an instance of a class. In our case, we want to read all the configuration inside TheSettings. into an instance of MyStettings.

1
2
3
4
var mySettings = new MySettings();
configuration.GetSection("TheSettings").Bind(mySettings);
Console.WriteLine("IsEnabled: " + mySettings.IsEnabled);
Console.WriteLine("Delay" + mySettings.Delay);

Conclusion

The process to setup a configuration file is not evident with .NET Core, it also changed a lot since the first release. But, it is way more flexible and lightweight than the solution provided with the full .NET Framework.

Here is how our final source code looks like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace SamepleConfiguration
{
    class Program
    {
        static void Main()
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                .AddJsonFile("appsettings.json", optional: false)
                .Build();

            var connectionString = configuration.GetConnectionString("Sample");
            Console.WriteLine(connectionString);

            var mySettings = new MySettings();
            configuration.GetSection("TheSettings").Bind(mySettings);
            Console.WriteLine("IsEnabled: " + mySettings.IsEnabled);
            Console.WriteLine("Delay" + mySettings.Delay);
        }
    }

		class MySettings
		{
		    public bool IsEnabled { get; set; }
		    public TimeSpan Delay { get; set; }
		}
}
This post is licensed under CC BY 4.0 by the author.