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就能访问到配置文件中配置节点的信息  

      

  • 相关阅读:
    P1242 新汉诺塔(hanio)
    P2878 [USACO07JAN]保护花朵Protecting the Flowers
    P2096 最佳旅游线路
    [P1363] 幻想迷宫
    在矩阵上跑最小生成树
    tarjan+topsort
    tarjan缩点
    【P3398]】仓鼠找sugar
    树形数组暴力
    解决跨域问题
  • 原文地址:https://www.cnblogs.com/huanglin101/p/6509124.html
Copyright © 2011-2022 走看看