index.md 3.3 KB

Examples Overview

This section provides various usage examples for Apq.Cfg.

Example Categories

Basic Examples

Integration Examples

Advanced Examples

Quick Examples

Simplest Usage

using Apq.Cfg;

var cfg = new CfgBuilder()
    .AddJson("config.json", level: 0, writeable: false)
    .Build();

var appName = cfg.Get("App:Name");
Console.WriteLine($"App Name: {appName}");

Multi-Source

var cfg = new CfgBuilder()
    .AddJson("config.json", level: 0, writeable: false)
    .AddYaml("config.yaml", level: 1, writeable: false, optional: true)
    .AddEnvironmentVariables(level: 2, prefix: "APP_")
    .Build();

Strongly-Typed Binding

public class DatabaseConfig
{
    public string Host { get; set; } = "";
    public int Port { get; set; } = 5432;
}

var dbSection = cfg.GetSection("Database");
var dbConfig = new DatabaseConfig
{
    Host = dbSection.Get("Host") ?? "localhost",
    Port = dbSection.Get<int>("Port")
};
Console.WriteLine($"Database: {dbConfig.Host}:{dbConfig.Port}");

Dependency Injection

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApqCfg(cfg => cfg
    .AddJson("config.json", level: 0, writeable: false)
    .AddEnvironmentVariables(level: 1, prefix: "APP_"));

builder.Services.ConfigureApqCfg<DatabaseConfig>("Database");

Dynamic Reload

var cfg = new CfgBuilder()
    .AddJson("config.json", level: 0, writeable: false, reloadOnChange: true)
    .Build();

cfg.ConfigChanges.Subscribe(e =>
{
    Console.WriteLine("Configuration updated!");
    foreach (var (key, change) in e.Changes)
    {
        Console.WriteLine($"  [{change.Type}] {key}");
    }
});

Encryption & Masking

using Apq.Cfg.Crypto;

var cfg = new CfgBuilder()
    .AddJson("config.json", level: 0, writeable: false)
    .AddAesGcmEncryptionFromEnv()  // Read key from environment variable
    .AddSensitiveMasking()          // Add masking support
    .Build();

// Encrypted value in config: { "Database": { "Password": "{ENC}base64..." } }
// Auto-decrypt on read
var password = cfg.Get("Database:Password");

// Use masked value for logging
Console.WriteLine($"Password: {cfg.GetMasked("Database:Password")}");
// Output: Password: myS***ord

Writable Configuration

var cfg = new CfgBuilder()
    .AddJson("config.json", level: 0, writeable: true, isPrimaryWriter: true)
    .Build();

// Modify configuration
cfg.Set("App:Name", "NewName");
cfg.Set("Database:Port", "5433");

// Save to file
await cfg.SaveAsync();

Run Sample Project

The repository includes complete sample code:

cd Samples/Apq.Cfg.Samples
dotnet run

Next Steps

Choose an example to learn more: