本节提供 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($"应用名称: {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($"数据库: {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("配置已更新!");
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() // 从环境变量读取密钥
.AddSensitiveMasking() // 添加脱敏支持
.Build();
// 配置文件中的加密值: { "Database": { "Password": "{ENC}base64..." } }
// 读取时自动解密
var password = cfg.Get("Database:Password");
// 日志输出时使用脱敏值
Console.WriteLine($"密码: {cfg.GetMasked("Database:Password")}");
// 输出: 密码: myS***ord
var cfg = new CfgBuilder()
.AddJson("config.json", level: 0, writeable: true, isPrimaryWriter: true)
.Build();
// 修改配置
cfg.Set("App:Name", "NewName");
cfg.Set("Database:Port", "5433");
// 保存到文件
await cfg.SaveAsync();
项目中包含完整的示例代码:
cd Samples/Apq.Cfg.Samples
dotnet run
选择您感兴趣的示例深入了解: