KeyInject 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package KeyInject --version 1.0.0                
NuGet\Install-Package KeyInject -Version 1.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="KeyInject" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add KeyInject --version 1.0.0                
#r "nuget: KeyInject, 1.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install KeyInject as a Cake Addin
#addin nuget:?package=KeyInject&version=1.0.0

// Install KeyInject as a Cake Tool
#tool nuget:?package=KeyInject&version=1.0.0                

<h1> <img src="icon.png" style="width: 50px; border: 1px solid grey;" /> <span>KeyInject</span> </h1>

KeyInject is a .NET library designed to inject values into configurations using regular expression patterns, with support for nested patterns.
This facilitates dynamic and flexible configuration management in .NET applications.

<h2 id="toc">πŸ“‹ Table of contents</h2>

<h2 id="features">🧩 Features</h2>

  • Regex-Based Injection: Utilize regular expressions to identify and replace placeholders in your configuration files.
  • Nested Pattern Support: Handle complex configurations with nested placeholders seamlessly.
  • Easy Integration: Designed for straightforward integration into existing .NET projects.
  • Supported versions: net8.0 and net9.0 and higher version supported

<h2 id="installation">πŸ“œ Installation</h2>

Install KeyInject using NuGet Package Manager:

Install-Package KeyInject

Or via the .NET CLI:

dotnet add package KeyInject

All versions can be found here.

<h2 id="quick-start">πŸš€ Quick Start</h2>

Look at actual examples here ./examples;

<h3 id="basic-example">Basic example</h3>

In appsettings.json:

{
  "ConnectionStrings": {
    "Main": "server=${SERVER};user=${DB_USER};password=${DB_PASSWORD}"
  }
}

In Environment variables:

SERVER=1.4.8.8
DB_USER=root-user
DB_PASSWORD=12345qwe_dontdothat

In Program.cs file:

using KeyInject;

var builder = WebApplication.CreateBuilder(args);

// Configuration order is up to you.
// Remember, that ConfigurationProviders overrides each other!
builder.Configuration.AddJsonFile("appsettings.json");
builder.Configuration.AddEnvironmentVariables();
// βœ… Add Key Injection exactly at the latest position 
builder.Configuration.AddKeyInject();

// add services ...

var app = builder.Build();

var conn = app.Configuration.GetConnectionString("Main");
await Console.Out.WriteLineAsync(conn);
// βœ… Output: server=1.4.8.8;user=root-user;password=12345qwe_dontdothat

await app.RunAsync();

<h2 id="basic-config">βš™οΈ Basic Configuration</h2> <h3 id="from-appsettings">From appsettings.json</h3>

KeyInject always enriches from appsettings.json.
It's not neccessary to provide json configuration.
By default, ${_} pattern will be used if no other patterns provided.
(All the patterns will be described below)

<h4 id="example-configuration">Example configuration</h4>

{
  "KeyInject": {
    // simply enable or disable globally 
    "Enabled": true,
    // ignore case of pattern key group >> ${IgNore_Case_Of_thIs_woRD}
    "IgnoreCase": true,
    // set how many time config will be injected to resolve circular dependencies
    "ReplaceRepeatCount": 10,
    // from preset patterns ${_}, <<_>> ...
    // if Patterns is empty, "${_}" pattern will be used anyway
    "Patterns": [
      "${_}", "{{_}}", "$<_>", "<<_>>", "!{_}!", "%_%"
    ],
    // adding custom regex pattern. 
    // warn! must use ?<key> regex group, see documentation.
    // no exception throw on bad regex.
    "RegexPatterns": [
      "!\\{(?<key>[^{}]+)\\}!"
    ],
    // adding custom prefixes
    "KeyPrefixes": [
      "PRE_", "DATABASE_"
    ]
  }
}

Extended configuration see in πŸ’‰ Dependency Injection part.

<h2 id="key-prefix">πŸ”‘ Key Prefix</h2>

Prefixes used to specify that we only want to replace keys starts with some value.
In example, for configured prefix DB_:
🚫 DATABASE_USER_PASSWORD - wont be replaced
βœ… DB_USER_PASSWORD - woill be replaced

πŸ’‘Notice!
If you specified prefixes, then only those patterns that start with this prefix will be replaced.

Can be registered with:

WebApplication.CreateBuilder(args)
    .Configuration.AddKeyInject(b => b
        .AddKeyPrefix("PRE_")
        .AddKeyPrefix("DATABASE_")
);

Or with appsettings:

{
  "KeyInject": {
    "KeyPrefixes": [
      "PRE_", "DATABASE_"
    ]
  }
}

<h2 id="patterns">🎭 Patterns</h2> <h3 id="preset-patterns">Preset patterns</h3>

πŸ’‘ Here is six default pattern names:
${_}    β€‚  {{_}}     $<_>
<<_>>     !{_}!     %_%

Can be registered with:

WebApplication.CreateBuilder(args)
    .Configuration.AddKeyInject(b => b
        .AddPresetPattern("${_}")
        .AddPresetPattern("$<_>")
);

Or with appsettings:

{
  "KeyInject": {
    "Patterns": [
      "${_}", "{{_}}", "$<_>", "<<_>>", "!{_}!", "%_%"
    ]
  }
}

⚠️ If no Pattern presented in explicit configuration will be used default: ${_}

Their detailed description:

  1. ${_}
  • regex: \$\{(?<key>[^\{\}]+)\}
  • example: ${SOMEKEY}, ${some_key_2}
  1. {{_}}
  • regex: \{\{(?<key>[^\{\}]+)\}\}
  • example: {{SOMEKEY}}, {{some_key_2}}
  1. $<_>
  • regex: \$<(?<key>[^<>]+)>
  • example: $<SOMEKEY>, $<some_key_2>
  1. <<_>>
  • regex: <<(?<key>[^<>]+)>>
  • example: <<SOMEKEY>>, <<some_key_2>>
  1. !{_}!
  • regex: !\{(?<key>[^{}]+)\}!
  • example: !{SOMEKEY}!, !{some_key_2}!
  1. %_%
  • regex: %(?<key>[^%]+)%
  • example: %SOMEKEY%, %some_key_2%

⚠️ Notice!
You must specify preset pattern name exactly in provided format!
Pattern names like "${...}" instead of ${_} is not supported!

Of course, you can use multiple patterns at the same time.

<h3 id="custom-patterns">πŸ”§ Custom patterns</h3>

You can use custom Regex patterns with builder or appsettings configuration.
You must to specify ?<key> regex group in pattern, like:

!\{(?<key>[^{}]+)\}!

⚠️ Group naming must be exactly: key

Custom pattern registration examples:

  • appsettings.json :
{
  "KeyInject": {
    "RegexPatterns": [
      "!\\{(?<key>[^{}]+)\\}!"
    ]
  }
}
  • with DI builder:
builder.Configuration.AddKeyInject(b => b
	// adding custom regex pattern. Warn! Must to use ?<key> regex group, see documentation.
	// no exception throw on bad regex.
	.AddRegexPattern(@"!\{(?<key>[^{}]+)\}!")
	// notice, adding built Regex CAN throw exception if regex text was incorrect
	.AddRegexPattern(new Regex(@"!\{(?<key>[^{}]+)\}!"))
);

<h2 id="nested-patterns">πŸͺ† Nested patterns</h2>

You can use nested patterns, by default supports 5 levels of nesting.
Here is an example of nesting:

  1. In appsettings.json
{
  "Connection": "${CONN}"
}
  1. In Environment variable:
CONN="server=${DB_IP};user=${DB_USER};password=${DB_PASSWORD}"
  1. In Vault config provider (or some else provider too):
DB_IP=1.2.3.4
DB_USER=rootuser
DB_PASSWORD=password123
  1. Result configuration string will be:
void DisplayConfig(IConfiguration config) {
	Console.WriteLine(config["Connection"]);
	// βœ… Output: server=1.2.3.4;user=rootuser;password=password123
}

⚠️ Default supported nesting for 5 levels, and it's enough for most cases.

You can change levels count with:

Configuration.AddKeyInject(b 
    => b.SetReplaceRepeatCount(10)
);

or in appsettings.json:

{
  "KeyInject": {
    "ReplaceRepeatCount": 10
  }
}

<h2 id="di">πŸ’‰ Dependency Injection</h2>

⚠️ Warning!
Use .AddKeyInject() after other Configuration Provides!

Example:

var builder = WebApplication.CreateBuilder(args);
// ... 
builder.Configuration.AddKeyInject(b => b
	// simply enable or disable globally 
	.SetEnabled(true)
	// adding custom prefixes
	.AddKeyPrefix("PRE_")
	.AddKeyPrefix("DATABASE_")
	// adding custom regex pattern. Warn! Must to use ?<key> regex group, see documentation.
	// no exception throw on bad regex.
	.AddRegexPattern(@"!\{(?<key>[^{}]+)\}!")
	// notice, adding built Regex CAN throw exception if regex text was incorrect
	.AddRegexPattern(new Regex(@"!\{(?<key>[^{}]+)\}!"))
	// from preset patterns ${_}, <<_>> ...
	.AddPresetPattern("${_}")
	// set how many time config will be injected to resolve circular dependencies
	.SetReplaceRepeatCount(10)
	// ignore case of pattern key group >> ${IgNore_Case_Of_thIs_woRD}
	.SetIgnoreCase(true)
	// choose yor custom config section instead default "KeyInject", first way:
	.EnrichFromAppSettings(builder.Configuration.GetSection("MyCustomSection"))
	// second way:
	.EnrichFromAppSettings(c => c.GetSection("MyCustomSection"))
);

<h2 id="contribution">β˜• Contribution</h2>

If you wanna to buy me a coffee πŸ˜ƒ, I will be grateful for any tokens in TON network:
πŸ’Ž noncommunicado.ton
πŸ’Ž UQD0zFgp0p-eFnbL4cPA6DYqoeWzGbCA81KuU6BKwdFmf8jv

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.1 49 2/20/2025
1.0.0 43 2/19/2025
0.0.2-alpha 39 2/19/2025
0.0.1-alpha 44 2/19/2025