In ASP.NET Core we are used to have multiple appsettings.json files with settings that differ per environment. I want to do the same in a Console Application. This makes debugging the application easier.

Multiple environments

First I would like to distinguish between environments. For ASP.NET Core I use local, development and production. Because I don’t have a development environment for my application, I’ll only use local.

Just like ASP.NET Core we will specify the environment as an environment variable. Right click on the project file > properties > click the debug tab. Add a new environmentĀ variable with the name ENVIRONMENT and the value Local.

Screenshot of the debug tab of a console application.

Multiple appsettings

Add the following json files to the root of your application:

  • appsettings.json
  • appsettings.Local.json

In my case I don’t use a special Production file, but I’ll override local setting values in the appsettings.Local.json file. Next we’ll need to create a settings class, something like:

public class AppSettings
{
    public string TempDirectory { get; set; }
}

Open the appsettings.json and add an app section:

{
    "App": {
        "TempDirectory": "c:\\temp\\rss-hero\\tmp\\"
    }
}

Note: I only add settings that differ from production in my local settings file. The system will override the settings of the main file.

Hook ’em up!

Next, we need to hook the settings up in the application. In a previous article I’ve demonstrated how to leverage dependency injection to support IOptions<T> and we’re building upon that. Install the following packages:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.DependencyInjection.Abstractions
  • Microsoft.Extensions.Options

Now add the this code to your Main class:

var environmentName = Environment.GetEnvironmentVariable("ENVIRONMENT");

// create service collection
var services = new ServiceCollection();

// build config
var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", false)
    .AddJsonFile($"appsettings.{environmentName}.json", true)
    .AddEnvironmentVariables()
    .Build();

// setup config
services.AddOptions();
services.Configure<AppSettings>(configuration.GetSection("App"));

// create service provider
var serviceProvider = services.BuildServiceProvider();

Settings can now be resolved using dependency injection or directly by doing:

var appSettings = serviceProvider.GetService<IOptions<AppSettings>>();

That’s all

Setting this up shouldn’t be more than copy-paste. For a more comprehensive overview of dependency injection for console applications check: Dependency injection (with IOptions) in Console Apps in .NET Core.