这种实例化依赖注入 class 的方式是否正确?

Is this way of instantiating a dependency injected class correct?

我是第一次实现依赖注入,遇到了“无法使用构造函数”的问题。我做了以下事情:

这是 class 的构造函数,需要 IHttpClientFactoryIMemoryCache 依赖项。 class 用于管理和缓存 OAuth 令牌。

private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;

public AuthManager(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache)
{
    _httpClientFactory = httpClientFactory;
    _memoryCache = memoryCache;
}

这是我在家庭控制器中实例化 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);
    ...
}
        

像这样使用依赖关系似乎很不对。 ¿我怎样才能更好地构建它?

首先。我会将 AuthManager 创建为在 AuthManager class 中实现的接口 (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;
    }