我是第一次實作依賴注入,遇到了“不能使用建構式”的問題。我做了以下事情:
這是需要IHttpClientFactory和IMemoryCache依賴項的類的建構式。這是一個管理和快取 OAuth 令牌的類。
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
public AuthManager(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache)
{
_httpClientFactory = httpClientFactory;
_memoryCache = memoryCache;
}
這就是我在 Home Controller中實體化AuthManager的地方:
// I used dependency injection here, too, and passed it through constructor.
private readonly ILogger<HomeController> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_memoryCache = memoryCache;
}
public async Task<IActionResult> Index()
{
//Code skipped for reading
//Passed the needed instances through parameter here
var authManager = new AuthManager(_httpClientFactory, _memoryCache);
...
}
使用這樣的依賴似乎很錯誤。? 我怎樣才能更好地構建它?
uj5u.com熱心網友回復:
首先。我會將 AuthManager 創建為在 AuthManager 類中實作的介面 (IAuthManager)。您可以在 startup.cs (.NET 5.0) 添加范圍服務:
services.AddScoped<IAuthManager, AuthManager>();
HomeController.cs 看起來像這樣:
public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, IAuthManager authManager)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_memoryCache = memoryCache;
_authManager = authManager;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464630.html
標籤:C# asp.net-mvc asp.net 核心 依赖注入
上一篇:為什么DelphiTOpenDialog無法在初始目錄中打開?
下一篇:重構:在子函式中委托友誼
