basic-usage.md 3.1 KB

Basic Usage

This guide covers the fundamental usage patterns of Apq.Cfg.

Building Configuration

Use CfgBuilder to create configuration instances:

using Apq.Cfg;

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

Builder Parameters

Parameter Description
level Priority level (higher overrides lower)
writeable Whether the source supports writing
optional Whether the source is optional
reloadOnChange Enable hot reload
isPrimaryWriter Mark as primary write target

Reading Values

String Values

// Get string value
string? value = cfg.Get("App:Name");

// With default value
string name = cfg.Get("App:Name") ?? "DefaultApp";

Typed Values

// Integer
int port = cfg.Get<int>("App:Port");

// Boolean
bool debug = cfg.Get<bool>("App:Debug");

// Double
double rate = cfg.Get<double>("App:Rate");

// DateTime
DateTime date = cfg.Get<DateTime>("App:StartDate");

Check Existence

if (cfg.Exists("App:Name"))
{
    var name = cfg.Get("App:Name");
}

Configuration Sections

Get Section

var dbSection = cfg.GetSection("Database");

var host = dbSection.Get("Host");
var port = dbSection.Get<int>("Port");

Nested Sections

var connSection = cfg.GetSection("Database:Connection");
var timeout = connSection.Get<int>("Timeout");

Enumerate Child Keys

var section = cfg.GetSection("Servers");
foreach (var key in section.GetChildKeys())
{
    var serverConfig = section.GetSection(key);
    Console.WriteLine($"Server: {key}");
}

Writing Values

Set Values

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

// Set value
cfg.Set("App:Name", "NewName");

// Set to specific level
cfg.Set("App:Port", "9090", targetLevel: 0);

Remove Values

cfg.Remove("App:TempKey");

Save Changes

// Save all changes
await cfg.SaveAsync();

// Save specific level
await cfg.SaveAsync(targetLevel: 0);

Batch Operations

Read Multiple Values

var keys = new[] { "App:Name", "App:Port", "App:Debug" };
var values = cfg.GetMany(keys);

foreach (var (key, value) in values)
{
    Console.WriteLine($"{key}: {value}");
}

Write Multiple Values

var updates = new Dictionary<string, string?>
{
    ["App:Name"] = "NewApp",
    ["App:Port"] = "8080",
    ["App:Debug"] = "false"
};

cfg.SetMany(updates);
await cfg.SaveAsync();

Microsoft.Extensions.Configuration Integration

// Convert to IConfigurationRoot
IConfigurationRoot msConfig = cfg.ToMicrosoftConfiguration();

// Use with existing code
var value = msConfig["App:Name"];

Next Steps