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

How to use Dependency Injection correctly for a constructor class with parameters in ASP.NET Core?

I have a UserRepository class that has a constructor with several parameters, including EshopContext, IValidateIdService, ICheckNull, and ILogger. I use this class in the UserController class, where I register dependencies in the service container (Dependency Injection container) for IRepository and UserRepository.

The problem is that Dependency Injection doesn’t seem to work as I would expect, and even though I have registered the services in the container, I still get an error forcing me to pass parameters to the UserRepository constructor in the UserController class.

What is the correct way to use Dependency Injection so that my service container automatically injects dependencies into the constructor of the UserRepository class? What am I doing wrong and how to fix it?

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

UserRepository.cs

private readonly EshopContext _context;
private readonly IValidateIdService _validateId;
private readonly ICheckNull _checkNull;
private readonly ILogger<UserRepository> _logger;

public UserRepository(EshopContext context, IValidateIdService validateId, ICheckNull checkNull, ILogger<UserRepository> logger)
{
    _context = context;
    _validateId = validateId;
    _checkNull = checkNull;
    _logger = logger;
}

UserController.cs

private readonly IRepository<User> _userRepository;

public UserController(IRepository<User> userRepository)
{
    _userRepository = userRepository;
}

Program.cs

builder.Services.AddSingleton<IValidateIdService, ValidateIdService>();
builder.Services.AddSingleton<ICheckNull, CheckForNullService>();

>Solution :

You are 90% there, just register the rest of your dependencies in Program.cs:

builder.Services.AddSingleton<IValidateIdService, ValidateIdService>();
builder.Services.AddSingleton<ICheckNull, CheckForNullService>();
builder.Services.AddSingleton<EshopContext, [IMPLEMENTATION];

For ILogger<UserRepository> you need to have added logging to your services. I’m assuming you already have the nuget package installed and set up.

And that’s it. DI "automagically" resolves any dependencies using the services you registered during start up.

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