首页 > Web开发 > 详细

.net core 学习笔记(5)-配置文件读取

时间:2017-03-06 13:39:52      阅读:294      评论:0      收藏:0      [点我收藏+]

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

  

 

.net core 学习笔记(5)-配置文件读取

原文:http://www.cnblogs.com/huanglin101/p/6509124.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!