Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this way of instantiating a dependency injected class correct?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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?

>Solution :

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading