This article is intended to demonstrate the use of Dependency injection in Asp.net core. How easily we can achieve DI in asp.net core application.
I am assuming you guys have a good understanding of dependency injections and why it is useful in the enterprise applications.
Some brief about the dependency injection for my friends who don’t have an idea about it.
In simple term dependency injection is the design pattern in which we don’t need to create the instance of classes manually. It will be automatically injected by the dependency injection service.
In Asp.net core framework Microsoft has provided the inbuilt support for dependency injections, which easy to initialize and use.
Let’s jump to the example code
I have created the simple.Net core MVC application for the demo purpose.
In the Employee controller, I will be using IEmployeeRepository for database operations.If you are not configuring the dependency injection then you are sure to the null reference exception for an employeeRepository object.
To make this work, we just need to add few lines of code in the Startup.cs file. Startup.cs file is available in the root folder. open the startup file and go to the ConfugureServices method.
Here you need to register the dependent services. As I have registered.
That’s all you need to do to add the dependency injections functionality in the application.
With Microsft asp.net core it’s too easy to configure the dependency injections, no need to register any third party framework and then do some initialization process. However, inbuild framework has some limitations as compared to the other frameworks like Castle Windsor, AutoFac, Unity. We can also configure the third party framework to achieve more features.
- Deependra is a Senior Developer with Microsoft technologies, currently working with Opteamix India business private solution. My Free time, I write blogs and make technical youtube videos. Having the good understanding of Service-oriented architect, Designing microservices using domain driven design.