1.13 配置框架:使用强类型对象承载配置数据.pdf

    appsettings.json:

    1. {
    2. "Key2": "Value2",
    3. "Key6": 0,
    4. "OrderService": {
    5. "Key1": "Order Key1",
    6. "Key5": true,
    7. "Key6": 200
    8. }
    9. }

    使用强类型对象配置:

    1. static void Main(string[] args)
    2. {
    3. var builder = new ConfigurationBuilder();
    4. builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    5. var configurationRoot = builder.Build();
    6. var config = new Config()
    7. {
    8. Key1 = "config key1",
    9. Key5 = false
    10. };
    11. //configurationRoot.Bind(config);
    12. configurationRoot.GetSection("OrderService").Bind(config,
    13. binderOptions => { binderOptions.BindNonPublicProperties = true; });
    14. Console.WriteLine($"Key1:{config.Key1}");
    15. Console.WriteLine($"Key5:{config.Key5}");
    16. Console.WriteLine($"Key6:{config.Key6}");
    17. }
    18. class Config
    19. {
    20. public string Key1 { get; set; }
    21. public bool Key5 { get; set; }
    22. public int Key6 { get; private set; } = 100;
    23. }

    效果:
    image.png

    由于一般都推荐使用强类型来管理配置,所以 Bind 方法在日常开发中用得比较多。