Conphig v1.0 published
Conphig (Nuget package), latest version: 2.1.1
Repetitive tasks are repetitive
There are a lot of things in coding that I end up doing over and over again. For those things, I keep a knowledge base: a set of private gists in GitHub for the purely code-based things, and a large number of how-to documents in Google Drive.
One of the things I have kept as a gist until now deals with getting runtime configuration for a command line tool, in a coherent way, from command line arguments, a JSON configuration file, environment variables or default settings. I want to be able to get settings from all those sources, with the right precedence order, efficiently. And I want the configuration specification to be a minimal piece of code.
NuGet Packages
For some reason, I just never thought of publishing prepackaged solutions like this properly. Well, there's this one npm package that I made about three years ago, mostly as an experiment, but other than that, I had never published packages to the world.
But now, there is the Conphig NuGet package that aims to solve runtime configuration loading for .NET 5 projects. And it just got bumped to version 1.0.0!
How to use it
After installing the Conphig
package, create a simple POCO class, and place your configuration items as properties inside. For each property, decorate it with JsonPropertyName
, CommandLine
, EnvironmentVariable
and Default
attributes to control how that property is loaded from JSON files, command line arguments and environment variables, and what the default value is. Like this:
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; }
}
}
Then, to load the configuration settings, just add a call to Config.Load<T>
to your application's startup code:
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 }");
}
}
}
I hope you will find my little tool useful.
The latest version of the code is always available in the GitHub repository.