ma.citi

A Coder's Blog

Configuration in .NET Core 1.0 Console Application

The first time I created a console application in .net core I had some troubles finding a simple documentation on how to use a json application settings file and retrieve configuration values from it.

In the following 3 simple steps I will explain how to do it..

Add an AppSettings.json file

After your Console App (.Net Core) is created, add a json file. I called it appsettings.json. Add some key/values and in its properties select “Copy if newer” for “Copy to Output Directory”

app settings

app settings

Create a Settings Provider

I created a class to build and provide an IConfiguration with keys and values

    public class SettingsProvider
    {
        private static IConfiguration _configuration;

        public static IConfiguration Configuration
        {
            get
            {
                if (_configuration == null)
                {
                    BuildConfiguration();
                }

                return _configuration;
            }
        }

        private static void BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            _configuration = builder.Build();
        }
    }

Retrieve values

Simply call the static Configuration property..

var uri = SettingsProvider.Configuration["RabbitMqUri"];