Vinicius Rocha

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.

> 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.

 {
  "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.

<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.

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.

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.

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.

> 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.

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.

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; }
		}
}