• NetCore配置详解(2)


    上一篇是Configuration对象功能,概念解释,这篇注重实践
    上一篇地址

    IOptions通过注入使用配置

    添加链接描述

    1.配置

    {
      "AppSettings": {
        "AccessKey": "111111",
        "SecretKey": "22222",
        "Bucket": "3333333",
        "Domain": "http://wwww.domain.com"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.配置对象

    public class AppSettings
    {
        public string AccessKey { get; set; }
    
        public string SecretKey { get; set; }
    
        public string Bucket { get; set; }
    
        public string Domain { get; set; }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    public void ConfigureServices(IServiceCollection services)
    {
    	services.AddOptions();
        var appSettings = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettings);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.通过构造注入

    public class UpoladService : IUpoladService
    {
        private AppSettings _appSettings;
    
        public UpoladService(IOptionsMonitor<AppSettings> appSettings)
        {
            _appSettings = appSettings.CurrentValue; //IOptions 需要每次重新启动项目加载配置,IOptionsMonitor 每次更改配置都会重新加载,不需要重新启动项目。
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    一、准备数据

    Student.json文件

    {
      "Name": "Alan.hsiang",
      "Age": 20,
      "Sex": "male",
      "Like": ["basketball","football","swimming"],
      "Score": {
        "LandLit": 90,
        "Mathematics": 99,
        "English": 50
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    二、创建IConfiguration实例

    IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).
    AddJsonFile("student.json").Build();
    
    • 1
    • 2

    三、获取配置的方式

    1.通过索引器进行读取

     var name = configuration["Name"]; //IConfiguration接口自带的索引器,只返回字符串类型。如:名字
     var like0 = configuration["Like:0"];//读取数组中第一个元素 如:第一个爱好
     var like2 = configuration["Like:2"];//读取数组中第三个元素 如:第三个爱好
     var landLit = configuration["Score:LandLit"];//获取字节点的属性值,如:语文成绩
    
    • 1
    • 2
    • 3
    • 4
     //通过索引器只能返回字符串类型的值,如果需要读取其他简单类型的对象,如:int,float等,
                //则可以通过GetValue()方法进行,具体如下所示:
                var age = configuration.GetValue<int>("Age");//获取其他数据类型,如:int,如:年龄
    
    • 1
    • 2
    • 3

    2.读取数组

    通过索引器和泛型方法,可以读取简单类型的对象,如果需要读取复杂对象【如:数组,列表等】,则需要使用绑定

     //获取整个数组,如:爱好
     var like = new List<string>();
     configuration.Bind("Like",like);
    
    • 1
    • 2
    • 3

    3.整体对象绑定

    以上示例都是对Json文件局部数据的读取,那么可以将整个文件转换为对象吗?这样直接操作对象将对很方便快捷。具体如下所示:

    首先复制整个Json文件的内容,然后依次点击【编辑–>选择性粘贴–>将JSON粘贴为类】菜单,如下所示:

    在这里插入图片描述

    默认生成的类名为RootObject,然后修改为Student,具体如下所示:

    namespace DemoCore
    {
        public class Student
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public string Sex { get; set; }
            public string[] Like { get; set; }
            public Score Score { get; set; }
        }
    
        public class Score
        {
            public int LandLit { get; set; }
            public int Mathematics { get; set; }
            public int English { get; set; }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    具体读取

     //2. 复杂读取
     var student = new Student();
     configuration.Bind(student);
     Console.WriteLine($"name={student.Name},age={student.Age},like= {string.Join(",", student.Like)},score={student.Score.English}");
    
    • 1
    • 2
    • 3
    • 4

    4. 读取环境变量

    设置环境变量,通过AddEnvironmentVariables,将环境变量添加入Configuration

    在这里插入图片描述

                IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddEnvironmentVariables().Build();
                Console.WriteLine(configuration["ASPNETCORE_ENVIRONMENT"]);
    
    • 1
    • 2

    5.获取子节点

    Json

    {
      "LTY" : {
        "Name": "Alan.hsiang",
        "Age": 20,
        "Sex": "male",
        "Like": [ "basketball", "football", "swimming" ],
        "Score": {
          "LandLit": 90,
          "Mathematics": 99,
          "English": 50
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    通过GetSection获取某个子节点的配置

                IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).
                    AddJsonFile("student.json", optional: false, reloadOnChange: true).Build();
                Score rootobject = configuration.GetSection("LTY:Score").Get<Score>();
                Console.WriteLine(rootobject.English);
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    6.通过注入获取配置(IOptions)

    .NET Core 引入了Options模式,使用强类型的类来表达配置项,提供了三种在不同场景下的使用接口:

    1. Options
      应用启动后无法读取修改的配置
      可以注入到任何依赖注入周期
    2. IOptionsSnapshot
      应用启动后可以读取修改的配置
      不支持以Singleton模式注入,Transient,Scoped 可以正常注入
    3. IOptionsMonitor
      应用启动后可以读取修改的配置
      Singleton,Transient,Scoped 三种注入周期都可以正常注入
      在这里插入图片描述
      同时提供 OnChange() 方法监听配置变更

    三种注入方式
    在这里插入图片描述

    设置配置信息

    在这里插入图片描述

    注入IOptions

    在这里插入图片描述

    使用

            public ActionResult<Score> ConfigurationSeventh()
            {
                var rootobject = _options.Value;
                Console.WriteLine(_options.Value.English);
                return rootobject;
            }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    R语言使用dplyr包的mutate函数将dataframe数据中的两个字符串数据列合并为一个新的数据列、两个数据列的内容合并起来形成一个新的数据列
    Linux高可用集群搭建
    Day03 Css的学习深入 background-X属性
    2024年经典【自动化面试题】附答案
    ZMQ之异步管家模式
    paperswithcode使用方法
    dreamweaver作业静态HTML网页设计 大学美食菜谱网页制作教程(web前端网页制作课作业)
    初识JSBridge:从原理到使用(android、ios、js三端互通的工具)
    程序员需要了解的先秦文学
    【ElasticSearch笔记】
  • 原文地址:https://blog.csdn.net/wsnbbdbbdbbdbb/article/details/126505856