Dependency Injection in ASP.NET Corev
Dependency Injection (shortform “DI”) is an ASP.NET Core technique to achieve loosely coupling between objects so that the applications can be maintained in an easy manner.
Here DOT NET runtime engine automatically injects objects of dependency classes, mainly through the constructor of the Controllers. Thus making the job of the developer much easier.
Create an Asp.Net Core Web App (Model-View-Controller)
Ceate an Interface inside the Repositoryy folder and call it IRepository
Create a Service Class Repository that implementn above interface IRepository
Controller - Without Dependency Injection:
What is the Problem in the above implementation?
If you see the Controller’s code above you will find it is Tightly Coupled to the Repository.cs class. The reason being that we are directly creating the object of Repository class using new keyword.
Suppose after some time a need arises to change the repository to another class called DbRepository.cs. So we will have to change the Controller’s code like this:
This is a problem of managing Tightly Coupled Components.
Why is tightly coupled code bad?
- It gives problems during the maintenance phase of the project. If one component changes then it will affect the other components also.
- There will be lots of problems when performing the Unit Testing of these components.
How DI Resolve this Issue?
- The Dependency Injection (DI) technique can solve these problems.
- The Controller class can be provided with the repository object automatically by ASP.NET Core and this will remove the tighlty coupling problem.
Implementing Dependency Injection in Above Controller
There are 2 steps to implement
1. Decouple the controller from the tiglht-coupled to loosely-coupled dependency.
2. Specifty how this new depenency (loosely-coupled) should be resolved by ASP.NET Core runtime.
With this we have added the loosely coupled dependency in the controller. If in future the need arises to change the repository then all you have to do is to create a new repository. We will not have to do a single change in the controller as it is now loosely-coupled to the repository.
One Last Change in Program.cs file
We have to tell ASP.NET Core how it should resolve the dependency of IRepository interface.
This service will now be created in Transient manner, such that whenever a request for “IRepository” object is made then it should be resolved by providing implementation of “Repository” type. The first parameter of AddTransient method is of type interface (here IRepository) while the second type being the implementation class (here Repository.cs).