appsettings.json:
{
"Key2": "Value2",
"Key6": 0,
"OrderService": {
"Key1": "Order Key1",
"Key5": true,
"Key6": 200
}
}
使用强类型对象配置:
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var configurationRoot = builder.Build();
var config = new Config()
{
Key1 = "config key1",
Key5 = false
};
//configurationRoot.Bind(config);
configurationRoot.GetSection("OrderService").Bind(config,
binderOptions => { binderOptions.BindNonPublicProperties = true; });
Console.WriteLine($"Key1:{config.Key1}");
Console.WriteLine($"Key5:{config.Key5}");
Console.WriteLine($"Key6:{config.Key6}");
}
class Config
{
public string Key1 { get; set; }
public bool Key5 { get; set; }
public int Key6 { get; private set; } = 100;
}
效果:
由于一般都推荐使用强类型来管理配置,所以 Bind 方法在日常开发中用得比较多。