文章出處
文章列表
ASP.NET Core 項目中有個appsettings.json
配置文件,用于存放一些配置信息,比如數據庫連接字符串等,但訪問的話,只能在 ASP.NET Core 項目中獲取,如果我們在其他項目類庫中,該怎樣獲取呢?
實現方式就是利用 ASP.NET Core DI,將配置信息注入到 IoC 中,通過構造函數獲取注入的對象。
appsettings.json
示例代碼:
{
"AppSettings": {
"AccessKey": "111111",
"SecretKey": "22222",
"Bucket": "3333333",
"Domain": "http://wwww.domain.com"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Error",
"System": "Information",
"Microsoft": "Information"
}
}
}
對應AppSettings
對象代碼:
public class AppSettings
{
public string AccessKey { get; set; }
public string SecretKey { get; set; }
public string Bucket { get; set; }
public string Domain { get; set; }
}
ConfigureServices
添加配置代碼:
public void ConfigureServices(IServiceCollection services)
{
var appSettings = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettings);
services.AddTransient<IUpoladService, UpoladService>();
// Add framework services.
services.AddMvc();
}
UpoladService
通過構造函數方式獲取注入對象:
public class UpoladService : IUpoladService
{
private AppSettings _appSettings;
public UpoladService(IOptionsMonitor<AppSettings> appSettings)
{
_appSettings = appSettings.CurrentValue; //IOptions 需要每次重新啟動項目加載配置,IOptionsMonitor 每次更改配置都會重新加載,不需要重新啟動項目。
}
}
參考資料:
文章列表
全站熱搜