• .net core Configuration 配置


    .net core 配置包括很多种 例如内存变量、命令行参数、环境变量以及物理文件配置和自定义配置

    物理文件配置主要有三种,它们分别是JSON、XML和INI,对应的配置源类型分别是JsonConfigurationSource、XmlConfigurationSource和IniConfigurationSource 这里主要讲JSON的配置

    读取配置文件 

    {

    "AllowedHosts": "*",

     "Logging": {
                       "IncludeScopes": false,
                       "LogLevel": {
                                     "Default": "Warning"
                                         }
                        }

       "Arry": [ { "Name": "zhangsan" }, { "Name": "lisi" }, { "Name": "wangwu" } ]
    }

    1.使用Key读取

    Configuration["AllowedHosts"]; // 结果 *

    Configuration["Logging:IncludeScopes"]; // 结果 false

    Configuration["Logging:LogLevel:Default"]; // 结果 Warning

    Configuration["Arry:0:Name"]; // 结果 zhangsan

    小结:读取嵌套的配置,使用冒号隔开;读取数组形式的配置,使用数组的下标索引,0表示第一个。

    2.使用GetValue<T>

    Configuration.GetValue<string>("AllowedHosts"); // 结果 *

    Configuration.GetValue<bool>("Logging:IncludeScopes"); // 结果 false

    小结:GetValue方法的泛型形式还有一个GetValue("key",defaultValue)重载。如果key的配置不存在,则为指定的默认值。

    3.使用Options

      配置文件

          {

            "Name": "zhangsan",          

               "Age": 22,

            "Company",{

                    "Id":1,

                    "Address":"中国 北京"

                  }
                         }

      public class User

       {

        public string Name { get; set; }

        public int Age { get; set; }

        public class Company

                {

                  public int Id {get;set;}

                  public string Address{get;set;}

                }

      }

    注入:

    services.Configure<User>(Configuration);

    services.Configure<Company>(Configuration.GetSection("Company"));

    services.Configure<Company>(Configuration.GetSection("User:Company"));

    读取:

      构造函数读取

     private readonly User _user;
     public GetConfig(IOptions<User> _options) 
     { _user = _option.Value; }
    ServiceProvider读取 serviceProvider.GetService<IOptions<User>>().Vlaue

    4.使用Bind
    var user = new User(); Configuration.Bind(user);
    var company=new Company();Configuration.GetSection("Conpany").Bind(company);
    4.使用Get<T>
    var user = Configuration.Get<User>();或者var commpany = Configuration.GetSection("Company").Get<Company>();
     
  • 相关阅读:
    angular1.5 组件学习 -- 4.2、组件的其他属性 transclude
    angular1.5 组件学习 -- 4.1、组件的其他属性 require
    angular1.5 组件学习 -- 3、组件的生命周期钩子
    angular1.5 组件学习 -- 2.2、组件间的交互:子向父
    angular1.5 组件学习 -- 2.1、组件间的交互:父向子
    angular1.5 组件学习 -- 1、组件的基本结构
    android内存优化相关1
    Android快速开发系列 10个常用工具类
    android Activity的启动模式
    [转载]Android系统开机画面的实现
  • 原文地址:https://www.cnblogs.com/Tony100/p/9317598.html
Copyright © 2020-2023  润新知