DotNetCore里一切都是依賴注入的,對於appsettings這個可擴展的配置對象也不例外,它位於項目根目錄,一般在startup里去注冊它,在類中通過構造方法注入來獲取當前的對象,以便去使用它,當然我們也可以自己去構建和使用它,下面我就來總結一下。
傳統方法,startup注入,構造方法使用
1 注意配置類
public class RedisConfiguration { #region 屬性成員 /// <summary> /// 文件上傳路徑 /// </summary> public string Host { get; set; } /// <summary> /// 允許上傳的文件格式 /// </summary> public string Password { get; set; } /// <summary> /// 圖片上傳最大值KB /// </summary> public int IsProxy { get; set; } #endregion }
2 在appsettings里添加它的內容
{ "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "RedisConfiguration": { "Host": "localhost:6379", "Password": "bobo123#", "IsProxy": "0" } }
3 在控制器里使用它,當然你可以在基類中定義它的使用方式,但注入的入口還是在構造方法上
public class ApiControllerBase : Controller { private readonly IOptions<RedisConfiguration> AppConfiguration; public ApiControllerBase(IOptions<RedisConfiguration> appConfiguration) { AppConfiguration = appConfiguration; } }
這時,你的AppConfiguration在被加載后,就有值了,是在程序運行時被注入進來的!
屬性中注入並且使用
appsetting的內容不變,只是在屬性中去封裝了配置注入與獲取的過程,注意,為了考慮性能,你可以把它的建立和獲取做成單例,這點我就不設計了!
public RedisConfiguration AppConfigurations
{
get
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
var sp = new ServiceCollection().AddOptions().Configure<RedisConfiguration>(
config.GetSection("RedisConfiguration")).BuildServiceProvider();
var _appConfiguration = sp.GetService<IOptions<RedisConfiguration>>();
return _appConfiguration.Value;
}
}
在控制器上,可以直接使用它了,我這個屬性是做在所有控制器的父類上的。
[HttpGet] public IEnumerable<string> Get() { return new string[] { AppConfigurations.Host, AppConfigurations.Password, AppConfigurations.IsProxy.ToString() }; }
感謝各位的閱讀!
對於.net core的研究我們還在繼續,希望core2.0,standard2.0不會讓我們失望!
聽說它已經實現了.net frameworks 4.6.1所有的功能!
