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