IC Improve Code Recipes

Recipe 6.1 · C#

From ConfigurationManager.AppSettings to IConfiguration

Problem

Settings are read as strings, deep inside business code, at the moment they are used. Missing or malformed values fail late and far from the cause. Classes can't be tested without a config file, and nobody can list which settings the application actually needs.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: string keys, parsing and defaults scattered everywhere.
public void RunImport()
{
    int batch = int.Parse(ConfigurationManager.AppSettings["BatchSize"]);
    string folder = ConfigurationManager.AppSettings["ImportFolder"];
    bool archive =
        ConfigurationManager.AppSettings["ArchiveFiles"] == "true";
    // ...
}

The improved recipe

Group related settings into a section in appsettings.json, bind the section to a class once at the edge of the application, and pass the typed object to the code that needs it.

JSON
{
  "Import": {
    "Folder": "D:\\Data\\Inbound",
    "BatchSize": 500,
    "ArchiveFiles": true
  }
}
C#
using System;
using Microsoft.Extensions.Configuration;

namespace ImproveCode.Configuration;

public sealed class ImportSettings
{
    public const string SectionName = "Import";

    public string Folder { get; set; } = string.Empty;

    public int BatchSize { get; set; } = 500;

    public bool ArchiveFiles { get; set; }
}

public static class AppConfiguration
{
    /// <summary>Builds configuration for tools that don't use the
    /// generic host. Later sources override earlier ones.</summary>
    public static IConfigurationRoot Build(string[] args)
    {
        string environment =
            Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
            ?? "Production";

        return new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{environment}.json",
                optional: true)
            .AddEnvironmentVariables()
            .AddCommandLine(args)
            .Build();
    }

    public static T GetRequiredSection<T>(
        this IConfiguration configuration, string sectionName)
        where T : class
    {
        return configuration.GetSection(sectionName).Get<T>()
            ?? throw new InvalidOperationException(
                $"Configuration section '{sectionName}' is missing.");
    }
}

public sealed class ImportJob(ImportSettings settings)
{
    public string Describe() =>
        $"Importing from {settings.Folder} in batches of " +
        $"{settings.BatchSize}";
}

Usage in a console tool:

C#
IConfigurationRoot config = AppConfiguration.Build(args);
var settings = config.GetRequiredSection<ImportSettings>(
    ImportSettings.SectionName);
var job = new ImportJob(settings);

How it works

ConfigurationBuilder merges several sources into one key-value view. The order matters: the JSON file sets defaults, the environment-specific file overrides some of them, environment variables override those, and command-line arguments win over everything. A key like Import:BatchSize can come from any of them, and the code that reads it doesn't care which.

Get<T>() (from the binder, part of Microsoft.Extensions.Configuration.Binder) creates the object and converts each value to the property type. "500" becomes an int, "true" becomes a bool. Property defaults (BatchSize = 500) apply when a key is absent, so the default lives in one obvious place instead of in every ?? "500" at every call site.

ImportJob takes ImportSettings in its constructor and never sees IConfiguration. That is the real improvement. The job can be unit tested with new ImportSettings { BatchSize = 2 }, and the list of settings it needs is visible in one class. Reading configuration only at the edge (Program.cs, the composition root) keeps string keys out of business code.

In ASP.NET Core and the generic host, you don't need AppConfiguration.Build at all. WebApplication.CreateBuilder and Host.CreateApplicationBuilder set up the same sources in the same order, plus user secrets in Development. Recipe 6.2 shows how to register typed settings with dependency injection.

Variations and pitfalls

  • Keys are case-insensitive and nested with a colon (Import:BatchSize). In environment variables, use a double underscore instead (Import__BatchSize), because colons aren't allowed in variable names on every platform.
  • configuration.GetValue<int>("Import:BatchSize", 500) is fine for a one-off value in Program.cs. Don't scatter it through the code base; that is AppSettings with a new name.
  • Binding fails quietly for misspelled keys: a property just keeps its default. Recipe 6.2 adds validation so a missing required value stops the app at startup.
  • Mark JSON files Copy if newer (the default for appsettings*.json in web projects, but not always in older console projects), or the file won't be next to the executable.
  • Arrays bind from JSON arrays or from indexed keys (Import:Extensions:0), which is how you override one element from an environment variable.

On .NET Framework

Microsoft.Extensions.Configuration and its JSON, environment and binder packages target .NET Standard 2.0, so they run on .NET Framework 4.6.1 and later. You can introduce appsettings.json and typed settings classes into a 4.8 app today, building the configuration once in Application_Start or Main. For keys that must stay in web.config, a small adapter that reads ConfigurationManager.AppSettings once and fills a settings class gives you the same benefit.