Conphig

#nuget #package #dotnet

Written by Anders Marzi Tornblad

Nuget logotypeConphig (Nuget package), latest version: 2.1.1: This helper library enables working with configuration data classes that automatically load settings from JSON files, from command line arguments, and from environment variables.

Installation

Using .NET CLI

dotnet add package Conphig --version 2.1.1

Using Package Manager Console

Install-Package Conphig -Version 2.1.1

Using Paket

paket add Conphig --version 2.1.1

Using the project file

<PackageReference Include="Conphig" Version="2.1.1" />

License

The license for Conphig is available on Nuget.org

How to use

Start by creating a simple POCO class, and place your configuration items as properties in it. For each property, use the JsonPropertyName, CommandLine, and EnvironmentVariable attributes to control how that property is deserialized from files, command line parameters, and environment variables.

using System.Text.Json.Serialization;
using ATornblad.Conphig;

namespace MyApp
{
    public class Setting
    {
        [JsonPropertyName("title")]
        [EnvironmentVariable("TITLE")]
        [CommandLine("-t", "--title")]
        public string Title { get; set; } = "Default title";
        
        [JsonPropertyName("verbose")]
        [EnvironmentVariable("VERBOSE")]
        [CommandLine("-v", "--verbose")]
        public bool Verbose { get; set; } = false;
        
        [JsonPropertyName("minAge")]
        [EnvironmentVariable("MIN_AGE")]
        [CommandLine("--min-age")]
        public int? MinAge { get; set; }
        
        [EnvironmentVariable("API_TOKEN")]
        public string? ApiToken { get; set; }
        
        [JsonPropertyName("categories")]
        [CommandLine("-c", "--category")]
        public string[]? Categories { get; set; }
        
        [JsonPropertyName("permissions")]
        [CommandLine("-p", "--permissions")]
        public PermissionLevels Permissions { get; set; }
    }
    
    [Flags]
    public enum PermissionLevels
    {
        None = 0,
        Read = 1,
        Create = 2
        Edit = 4
        Manage = 8
        Delete = 16
    }
}

Then, in your Main method (or somewhere else that makes sense given your app startup code), add a call to Config.Load<T>:

using ATornblad.Conphig;

namespace MyApp
{
    public class Program
    {
        public void Main(string[] args)
        {
            var config = Config.Load<Setting>();
            Console.WriteLine($"Title: {config.Title}");
            Console.WriteLine($"Verbose Output: {config.Verbose}");
            Console.WriteLine($"Minimum Age: {config.MinAge}");
            Console.WriteLine($"Api Token: {config.ApiToken }");
        }
    }
}

Configuration source precedence

When populating a configuration object, the different possible sources have the following precedence:

Configuration file filename

When calling Config.Load<T> you have the option of providing a filename, like this: Load<Settings>("config.json"). If no filename is provided, the name of the configuration class is transformed to a filename:

You also have the option of overriding the default filename for a configuration class, by applying the Filename attribute:

[Filename("config.json")]
public class SomeConfiguration
{
    ...
}

Documentation

Config class

The Config class is responsible for loading configuration according to specifications in attributes.

Config.Load<T>

Creates an instance of the T class and populates it.

CommandLine attribute

The CommandLine attribute lets you specify which command line switch(es) to use for the property. For bool properties, the existance of the switch makes the value true. You can specify multiple switches, beginning with at least one dash. For array properties, the user can provide the same switch multiple times.

[CommandLine(SWITCH {, SWITCH, ...})]
public TYPE NAME { get; set; }

Usage example from command line:

# Sets Verbose to true, Title, Categories (array with three items) and MinAge
myprogram -v -t "About API programming in .NET" -c API -c .NET -c Programming --min-age 15 -p Read,Create,Edit

EnvironmentVariable attribute

The EnvironmentVariable attribute lets you specify which environment variable to use for the property. Setting array properties from environment variables is not supported.

[EnvironmentVariable(VARIABLE_NAME)]
public TYPE NAME { get; set; }

Filename attribute

The Filename attribute lets you override the default filename to use for json configuration files.

[Filename(FILENAME)]
public class CLASSNAME

JsonPropertyName attribute

The JsonPropertyName attribute is used for declaring property names to use in json configuration files. It exists in the System.Text.Json.Serialization namespace and is not part of the Conphig package.

The latest version of the code is always available in the GitHub repository.