Issue
This Content is from Stack Overflow. Question asked by Musaffar Patel
I have for the first time started using services and dependency injection in my c# project.
I have the following Interface and class:
public interface IUserService
{
...
}
public class UserService : IUserService
{
...
}
so far nothing confusing.
but then I take advantage of DI as follows:
public class UsersController : ControllerBase
{
private IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
}
This works as expected. However I am struggling to understand how the compiler would know the the userService parameter passed to the UsersController constructor should be an instance of the UserService class, as the type for the parameter is IUserService. Adding furthermore to my confusion is the fact that I can make use of _userService as though it is an instance of UserClass even though once again it is declared as IUserService.
Does it have anything to do with the line below in my Program.cs file?
services.AddScoped<IUserService, UserService>();
I’m hoping for a simple explanation that isn’t too technical as I am still familiarizing myself with some of the very basic concepts of the language and .NET framework.
Solution
The interface IUserService
declares members (methods, properties, events) any implementation must provide. Therefore, it does not matter which class is passed to UsersController
as long as it implements this interface. Any class implementing IUserService
will work. The class UserService
is said to be assignment compatible to IUserService
.
The compiler does not know that UsersController
must be initialized with a UserService
. The Dependency Injection Container is doing this and it is indeed the line services.AddScoped<IUserService, UserService>();
which tells it to do so.
The point of dependency injection is to make the consuming code independent of a concrete implementation. In times of procedural programming every piece of code tended to depend on every other one, making it extremely hard to find an eliminate bugs and to evolve the code. Dependency injection, on the other hand, leads to a loose coupling between the classes.
See also:
- OOP Concepts in C# – Polymorphism, Interfaces and Inheritance.
- Dependency injection in ASP.NET Core (Microsoft Learn).
This Question was asked in StackOverflow by Musaffar Patel and Answered by Olivier Jacot-Descombes It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.