NetCore配置详解(2)

发布于:2023-01-04 ⋅ 阅读:(159) ⋅ 点赞:(0)

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

IOptions通过注入使用配置

添加链接描述

1.配置

{
  "AppSettings": {
    "AccessKey": "111111",
    "SecretKey": "22222",
    "Bucket": "3333333",
    "Domain": "http://wwww.domain.com"
  }
}

2.配置对象

public class AppSettings
{
    public string AccessKey { get; set; }

    public string SecretKey { get; set; }

    public string Bucket { get; set; }

    public string Domain { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
	services.AddOptions();
    var appSettings = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettings);
}

3.通过构造注入

public class UpoladService : IUpoladService
{
    private AppSettings _appSettings;

    public UpoladService(IOptionsMonitor<AppSettings> appSettings)
    {
        _appSettings = appSettings.CurrentValue; //IOptions 需要每次重新启动项目加载配置,IOptionsMonitor 每次更改配置都会重新加载,不需要重新启动项目。
    }
}

一、准备数据

Student.json文件

{
  "Name": "Alan.hsiang",
  "Age": 20,
  "Sex": "male",
  "Like": ["basketball","football","swimming"],
  "Score": {
    "LandLit": 90,
    "Mathematics": 99,
    "English": 50
  }
}

二、创建IConfiguration实例

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

三、获取配置的方式

1.通过索引器进行读取

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

2.读取数组

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

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

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; }
    }

}

具体读取

 //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}");

4. 读取环境变量

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

在这里插入图片描述

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

5.获取子节点

Json

{
  "LTY" : {
    "Name": "Alan.hsiang",
    "Age": 20,
    "Sex": "male",
    "Like": [ "basketball", "football", "swimming" ],
    "Score": {
      "LandLit": 90,
      "Mathematics": 99,
      "English": 50
    }
  }
}

通过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);

在这里插入图片描述

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;
        }

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到