zoukankan      html  css  js  c++  java
  • .net core 学习笔记(5)-配置文件读取

    1.在appsetting下新增一个配置节点:

    "KeyStrings": {
        "key": "abc",
        "value": "test"
      },
    

    2.新增类文件 KeyStrings.cs

    public class KeyStrings{
      public string key{get;set}
      public string value{get;set;}    
    }
    

    3.添加读取配置文件的类及接口文件KeyReposiroty.cs,IKeyRepository.cs

    public class KeyReposiroty:IKeyReposiroty
    {
    
      protected readonly   KeyStrings _keystrings;
      public KeyReposiroty(IOptions<KeyStrings> keystrings){
        _keystrings=keystrings
      }
    
      public virtual KeyStrings MyKeyStrings
            {
                get
                {               
                    return _keystrings;
                }
            }
      
          
    }
    

      

    public interface IKeyReposiroty
    {
    
       KeyStrings MyKeyStrings{get;}
                   
    }
    

      

    4.新增扩展方法

    public static IServiceCollection GetKeyString(this IServiceCollection services, IConfigurationSection configuration)
            {          
                services.Configure<KeyStrings>(configuration);
                services.AddSingleton<IKeyRepository,KeyRepository>(); //无接口的时候进行类的注入:services.AddSingleton<KeyRepository>();
            return services;
        }

    5.在Startup中调用扩展方法进行依赖注入  

    public void ConfigureServices(IServiceCollection services)
    {         
    services.GetKeyString(Configuration.GetSection("KeyStrings"));
    }

    6.现在通过IkeyRepository的MyKeyStrings就能访问到配置文件中配置节点的信息  

      

  • 相关阅读:
    洛谷 P1195 口袋的天空
    洛谷 P3144 [USACO16OPEN]关闭农场Closing the Farm_Silver
    Bzoj3277 串
    Bzoj1312 / POJ3155 Neerc2006 Hard Life
    Bzoj2655 calc
    51Nod 1228 序列求和
    洛谷P2901 [USACO08MAR]牛慢跑Cow Jogging
    Bzoj1042 [HAOI2008]硬币购物
    Bzoj3884 上帝与集合的正确用法
    Bzoj4161 Shlw loves matrixI
  • 原文地址:https://www.cnblogs.com/huanglin101/p/6509124.html
Copyright © 2011-2022 走看看