This guide covers the fundamental usage patterns of Apq.Cfg.
Use CfgBuilder to create configuration instances:
using Apq.Cfg;
var cfg = new CfgBuilder()
.AddJson("config.json", level: 0, writeable: false)
.Build();
| 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 |
// Get string value
string? value = cfg.Get("App:Name");
// With default value
string name = cfg.Get("App:Name") ?? "DefaultApp";
// 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");
if (cfg.Exists("App:Name"))
{
var name = cfg.Get("App:Name");
}
var dbSection = cfg.GetSection("Database");
var host = dbSection.Get("Host");
var port = dbSection.Get<int>("Port");
var connSection = cfg.GetSection("Database:Connection");
var timeout = connSection.Get<int>("Timeout");
var section = cfg.GetSection("Servers");
foreach (var key in section.GetChildKeys())
{
var serverConfig = section.GetSection(key);
Console.WriteLine($"Server: {key}");
}
// 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);
cfg.Remove("App:TempKey");
// Save all changes
await cfg.SaveAsync();
// Save specific level
await cfg.SaveAsync(targetLevel: 0);
var keys = new[] { "App:Name", "App:Port", "App:Debug" };
var values = cfg.GetMany(keys);
foreach (var (key, value) in values)
{
Console.WriteLine($"{key}: {value}");
}
var updates = new Dictionary<string, string?>
{
["App:Name"] = "NewApp",
["App:Port"] = "8080",
["App:Debug"] = "false"
};
cfg.SetMany(updates);
await cfg.SaveAsync();
// Convert to IConfigurationRoot
IConfigurationRoot msConfig = cfg.ToMicrosoftConfiguration();
// Use with existing code
var value = msConfig["App:Name"];