標籤: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就能訪問到設定檔中配置節點的資訊
.net core 學習筆記(5)-設定檔讀取