标签:app virt str configure readonly return prot 信息 pre
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就能访问到配置文件中配置节点的信息
标签:app virt str configure readonly return prot 信息 pre
原文地址:http://www.cnblogs.com/huanglin101/p/6509124.html