This article intends to show the use of asp.net core dependency injection. Not to mention, you will understand how easily we can achieve DI in an asp.net core application. In fact, I assume that you guys understand dependency injections and their use in enterprise applications well.
Overview of ASP.NET Core Dependency Injection
In simple terms, dependency injection is a design pattern, wherein you need not to create an instance of classes manually. And, the dependency injection service automatically injects the instance.
In fact, with an inbuilt support for dependency injections, Microsoft makes initialization and use easier in Asp.net core framework.
To proceed further, let’s jump to the example code. Here’s a sample.Net core MVC application created for demo purpose.
Here in, I will use IEmployeeRepository for database operations in the Employee controller. However, if you have not configured the dependency injection, you are sure to null reference exception for an employeeRepository object.
To make this work, we need to add a few lines of code in the Startup.cs file. Startup.cs file is available in the root folder. To proceed further, open the startup file and go to the ConfugureServices method. Lastly, you will need to register the dependent services as I have registered.
Altogether, that’s all you need to do to add the dependency injection functionality in the application.
In conclusion, it’s easy to configure the dependency injections with Microsoft asp.net core. And also, you need not to register any third party framework and follow the initialization process. However, an inbuilt framework has limitations as compared to other frameworks like Castle Windsor, AutoFac, and Unity. Also, we can unlock more features of the asp.net core dependency injection by configuring a 3rd party framework.
Do you think this was a useful article for you? Also, feel free to provide your comments and concerns in the below comment section.