This section provides various usage examples for Apq.Cfg.
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}");
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();
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}");
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");
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}");
}
});
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
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();
The repository includes complete sample code:
cd Samples/Apq.Cfg.Samples
dotnet run
Choose an example to learn more: