zoukankan      html  css  js  c++  java
  • NETCore下IConfiguration和IOptions的用法

    新建一个NETCore Web API项目,在Startup.cs里就会开始使用IConfiguration和IOptions了,我们来看看如何使用。
    IConfiguration 是用来加载配置值的,可以加载内存键值对、JSON或XML配置文件,我们通常用来加载缺省的appsettings.json .

    1. 注入IConfiguration

    执行到Startup的时候,IConfiguration已经被注入到services了,不需要我们额外添加注入的代码,缺省就是读取appsettings.json文件,你可以理解在Startup.cs里有隐藏的注入代码类似如下:

    var builder = new ConfigurationBuilder()
                   .SetBasePath(env.ContentRootPath)
                   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                   .AddEnvironmentVariables();
    Configuration = builder.Build();
    services.AddSingleton<IConfiguration>(Configuration);
    

    2. 使用IConfiguration

    我们先设置一下appsettings.json

    {
      "test1":"v1",
      "test2":{
        "key1":"v2",
        "key2":"v3",
        "key3":4,
        "key4":true
      }
    }
    

    在Controller里直接在构造函数里传入IConfiguration


     
    image.png

    可以看到获取appsettings.json里的值很简单,如果是对象值只需要加一个冒号。
    更好的方式去获取一个对象是用IOptions,我们接下来看看。

    3. 注入IOptions

    先定义一个OptionSample类需要实现IOptions接口:


     
    image.png

    然后,注入代码很简单

    services.Configure<OptionSample>(Configuration.GetSection("test2"));
    

    这句话等同于以下代码

    OptionSample sample = new OptionSample();
    sample.key1 = Configration["test2:key1"];
    sample.key2 = Configration["test2:key2"];
    sample.key3 = Configration["test2:key3"];
    sample.key4 = Configration["test2:key4"];
    services.AddSingle<IOptions<OptionSample>>(sample);
    

    4. 使用IOptions

    这个同样在构造函数里传参数


     
    image.png

    大家可以看到在NETCore中无处不在的依赖注入。源码参考Github



    作者:voxer
    链接:https://www.jianshu.com/p/b9416867e6e6
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    Centos 7 开放查看端口 防火墙关闭打开
    idea将项目导出为war包
    webstorm 注册服务器
    centos 6.4系统双网卡绑定配置详解
    centos所有版本镜像下载地址
    浅谈Nginx负载均衡与F5的区别
    勒索病毒应急响应计划
    Python网络编程常用代码
    Flask debug 模式 PIN 码生成机制安全性研究笔记
    Pythonic定义
  • 原文地址:https://www.cnblogs.com/nimorl/p/12570823.html
Copyright © 2011-2022 走看看