.NET Core Dependency Injection
Building fully coherent and decoupled Web applications is a vital skill for every developer. Today I will walk you through how to implement DI into your .NET core web application.
1- Create a .NET Core (Model-View-Controller) project.
In Visual studio pick the corresponding project that is shown in the image below.
2-Adding models and a mock repository
After you have created your project, the next step is to add a simple model and a mock repository to demonstrate the concept.
a-Adding a simple model
b- creating our repository Interface and concrete class
Here we added a generic Repository interface and our MockRepositry is implementing the interface. As you can see we are not fetching any data from a database. We’re following this approach for proof of concept.
3- Specifying our IoC in Startup.cs
In Startup.cs in ConfigureServices method, you need to tell the application on startup, whenever there is a request of IMockRepository<Avatar> give us a MockRepository Instance.
As you can see we are asking the service to provide us with a MockRepsotiry Instance on every request. There are various types of instantiations like Singleton or Transient that I will not cover in this demostrtation.
4-Igniting things up!!
When you first created the project the startup will provide you with a default controller called “HomeController”. In Home controller, we will add a private read-only property of type IMockRepository<Avatar> in our scope level class.
private readonly IMockRepository<Avatar> _repo;
Now. once you have your repository property implemented we will need to inject an instance of the same type in the Home constructor.
As you can see once a request is instantiated our Interface is getting injected with an instance of MockRepsotiry. Also, notice the _moickcontext list that we had made in our MokcRespoitory class.
6-Calling the Repository
In the Index method, I'm invoking the GetAll(); method, and as you can see the data we have in _mockContext list is retrieved.
Hope you enjoyed this story.