当前位置: 首页 > article >正文

.Net Core配置系统

目录

Json文件配置

读取配置原始方法

绑定读取配置

用法


  1. 传统Web.config配置的缺点
  2. 为了兼容,仍然可以使用Web.config和ConifgurationManager类,但不推荐
  3. .NET中的配置系统支持丰富的配置源,包括文件(json、xml、ini等)、注册表、环境变量、命令行、Azure Key Vault等,还可以配置自定义配资源。可以跟踪配置的改变,可以按照优先级覆盖。

Json文件配置

  1. 创建一个json文件,文件名随意,比如config.json,设置“如果较新则复制”
  2. NuGet安装Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json
  3. 编写代码,先用简单的方式读取配置

{
  "name": "ljy",
  "age": "18",
  "proxy": {
    "address": "aa",
    "port": "80"
  }
}

读取配置原始方法
//创建配置构建器实例
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
//添加JSON配置文件
configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
//构建配置根对象
IConfigurationRoot config = configurationBuilder.Build();
//读取“name”配置项
string name = config["name"];
//读取“proxy:address”配置项
string proxyAddress = config.GetSection("proxy:address").Value;
  • optional:表示文件是否可选,建议optional设置为false,这样写错可及时发现
  • reloadOnChange:表示如果文件修改了,是否重新加载配置
绑定读取配置
  1. 可以绑定一个类,自动完成配置的读取
  2. NuGet安装:Microsoft.Extensions.Configuration.Binder
  3. Server server=configRoot.GetSection("proxy").Get<Server>()
class Program
{
    static void Main(string[] args)
    {
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
        IConfigurationRoot configRoot = configurationBuilder.Build();
        //1
        //string name = configRoot["name"];
        //Console.WriteLine($"name={name}");
        //string address = configRoot.GetSection("proxy:address").Value;
        //Console.WriteLine($"address={address}");

        //2
        //Proxy proxy = configRoot.GetSection("proxy").Get<Proxy>();
        //Console.WriteLine($"{proxy.Address},{proxy.Port}");

        //3
        Config config =configRoot.Get<Config>();
        Console.WriteLine(config.Name);
        Console.WriteLine(config.Proxy.Address);
    }
}
class Config
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Proxy Proxy { get; set; }
}
class Proxy
{
    public string Address { get; set; }
    public int Port { get; set; }
}
用法
  1. 推荐使用选项方式读取,和DI结合更好,且更好利用“reloadonchange”机制
  2. Nuget安装:Microsoft.Extensions.OptionsMicrosoft.Extensions.Configuration.BinderMicrosoft.Extensions.ConfigurationMicrosoft.Extensions.Configuration.Json
  3. 读取配置的时候,DI要声明IOptions<T>、IOptionsMonitor<T>、IOptionsSnapshot<T>等类型。IOptions<T>不会读取到新的值;和IOptionsMonitor相比,IOptionsSnapshot会在同一个范围内(比如ASP.NET Core一个请求中)保持一致。建议用IOptionsSnapshot
class Program
{
    static void Main(string[] args)
    {
        ServiceCollection services = new ServiceCollection();
        services.AddScoped<TestController>();
        services.AddScoped<Test2>();

        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
        IConfigurationRoot configRoot = configurationBuilder.Build();
        //使用services.AddOptions()方法将选项框架注册到服务容器中,Configure<Config>方法来配置Config类的实例。configRoot.Bind(e)是将配置根绑定到Config类的实例上,这样就可以从配置文件中读取相应的配置值并填充到Config类的属性中
        services.AddOptions()
            .Configure<Config>(e => configRoot.Bind(e))
            .Configure<Proxy>(e => configRoot.GetSection("proxy").Bind(e));

        using (var sp = services.BuildServiceProvider())
        {
            var c = sp.GetRequiredService<TestController>();
            c.Test();
            var c2 = sp.GetRequiredService<Test2>();
            c2.Test();
        }
    }
}

class Config
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Proxy Proxy { get; set; }
}

class Proxy
{
    public string Address { get; set; }
    public int Port { get; set; }
}

class TestController
{
    private readonly IOptionsSnapshot<Config> optConfig;
    public TestController(IOptionsSnapshot<Config> optConfig)
    {
        this.optConfig = optConfig;
    }

    public void Test()
    {
        Console.WriteLine(optConfig.Value.Age);
        Console.WriteLine(optConfig.Value.Proxy.Port);
    }
}

class Test2
{
    private readonly IOptionsSnapshot<Proxy> optProxy;
    public Test2(IOptionsSnapshot<Proxy> optProxy)
    {
        this.optProxy = optProxy;
    }

    public void Test()
    {
        Console.WriteLine(optProxy.Value.Address);
    }
}


http://www.kler.cn/a/458461.html

相关文章:

  • 力扣251题详解:展开二维向量的多种解法与模拟面试
  • 无法验证服务器身份是什么意思?
  • 关于harmonyOS Next中状态管理的学习
  • 探秘 Neat 公司的自动测试架构:如何高效创造与价值保持
  • ThinkPHP 8开发环境安装
  • 【IC验证】verilog及systemverilog特殊特性的分析
  • uniapp-vue3(下)
  • Direct Preference Optimization: Your Language Model is Secretly a Reward Model
  • MIT实验笔记冲刺3:页表操作(理论部分)
  • 解锁ChatGPT潜力:打造属于你的AI助手
  • 基于Springboot的高校办公室行政事务管理系统【附源码】
  • Linux 的信号机制
  • 使用C#生成一张1G大小的空白图片
  • Django REST framework 源码剖析-路由详解(Routers)
  • Docker 开启远程端口访问2375
  • Java的责任链模式在项目中的使用
  • 如何优化求职简历从模板选择到面试准备
  • LeetCode 203:根据值删除节点
  • HDLBits训练6
  • Java爬虫实战:获取亚马逊商品详情