• 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
  • 相关阅读:
    MYSQL一站式学习,看完即学完
    Python开发环境及常用Web框架
    植物大战僵尸杂交版v2.1最新直装版,苹果+安卓+PC+防闪退工具+修改工具+高清工具+通关存档整合包更新
    【JavaScript高级】05-JavaScript中with、eval语句及严格模式的使用
    [实验报告]--基于端口安全
    Selenium 三种等待方式详解 (强制等待、隐式等待、显示等待)
    数字文档管理对您的业务是否具有成本效益?
    Maven的安装与配置(设置本地Maven仓库、IDEA配置Maven)
    中转服务器是干嘛的?
    适用于多类移动场景的融合认证机制设计
  • 原文地址:https://blog.csdn.net/wsnbbdbbdbbdbb/article/details/126505856