Skip to content

pet-toys/templated-configuration-provider

Templated configuration provider

Unit Test NuGet Version NuGet Downloads

Features

This library adds its own ConfigurationProvider to the configuration builder. This provider can override values from previously registered providers. New values are computed according to the template (if defined).

  • Absolute references to values are supported.
  • Relative links from the same or parent sections are supported.
  • Configuration reload are supported (IOptionMonitor<>).

Template examples

Configuration:

{
  "ConnectionStrings": {
    "DbConnection1": "Host=localhost;Password={ConnectionStrings:DbConnection:Password};",
    "DbConnection2": "Host=localhost;Password={DbConnection:Password};",
    "DbConnection:Password": "Pa$Sw0{rD"
  }
}

Result:

{
  "ConnectionStrings": {
    "DbConnection1": "Host=localhost;Password=Pa$Sw0{rD;",
    "DbConnection2": "Host=localhost;Password=Pa$Sw0{rD;",
    "DbConnection:Password": "Pa$Sw0{rD"
  }
}

More examples in unit tests.

Getting started

  • Provider is installed from NuGet. dotnet add package PetToys.TemplatedConfigurationProvider
  • Add a using statement to PetToys.TemplatedConfigurationProvider
  • Add a provider to the configuration builder, preferably by using the AddTemplatedConfiguration() extension method.

Examples of using

using PetToys.TemplatedConfigurationProvider;

/* snip ... */

    IConfigurationRoot configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddUserSecrets(Assembly.GetExecutingAssembly())
        .AddEnvironmentVariables()
        .AddTemplatedConfiguration()
        .AddCommandLine(args)
        .Build();
using PetToys.TemplatedConfigurationProvider;

/* snip ... */

    var builder = WebApplication.CreateBuilder(args);
    builder.Configuration.AddTemplatedConfiguration(opt =>
    {
        opt.TemplateCharacterStart = '[';
        opt.TemplateCharacterEnd = ']';
    });

Provided under the Apache License, Version 2.0.