Home > Mobile >  Is this way of instantiating a dependency injected class correct?
Is this way of instantiating a dependency injected class correct?

Time:04-26

I was implementing dependency injection for the first time, and encountered with the "can't use the constructor" issue. I made a get around doing the following:

This is the constructor for the class that needs IHttpClientFactory and IMemoryCache dependencies. It's a class to manage and cache OAuth tokens.

private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;

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

And this is where I instantiate AuthManager, at Home Controller:

// 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);
    ...
}
        

It seems so wrong using dependency like this. ¿How can I better build this?

CodePudding user response:

First of all. I would create AuthManager as Interface (IAuthManager) which is implemented in AuthManager class. You can than, in startup.cs (.NET 5.0) add a scoped service:

services.AddScoped<IAuthManager, AuthManager>();

HomeController.cs would look like this:

public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, IAuthManager authManager)
    {
        _httpClientFactory = httpClientFactory;
        _logger = logger;
        _memoryCache = memoryCache;
        _authManager = authManager;
    }
  • Related