Implement and register dependency injection in ASP .NET CORE/.NET 6
Before start, I would like to explain few point about the .NET 6 (.NET core new Version 6)
- On the creation of the Web API .NET Core project, Startup class is not present.
- Startup class get merged with Program class.
- All configuration and services will be configured in the Program class.
- Build in support of Swagger.(Tick the checkbox of “Enable OpenAPI support” while creating the project)
Let’s discuss about the Dependency injection(DI) and how can we register it in the container class.
.NET core support build in dependency injection(DI) which we can achieve by below approaches:
- Constructor injection
- Property injection
- Method injection
In this articles, we will learn
- Inject the dependency injection using first method(Constructor Injection)
- Register the interfaces and classes in the container class.
To start, few things are required:
- Visual studio 22
- .NET 6 (.NET Core)
- Swagger for testing the API
Let’s go and start to implement the multiple interface in the .NET 6/.NET Core.
- Search and select a ASP .NET Core Web API project from the create a new project tabs.
- Click next and add the project name
- Select .NET 6.0 as framework and click on the check box of “Enable OpenAPI support” as its build in feature of swagger for testing the API.
Once project get created, then move it to next step.
STEP1- Created interfaces — IEmployeeDetails and IDepartmentDetails
STEP 2 — Create service and implement the interface in the classes as below:
STEP3 — Need to call the business logic in the controller. For this we need to inject the dependency in the controller layer using Constructor injection
STEP 4 — Calling the service using the injector
NOTE: Try to run the code, you will get the run time exception.
System.InvalidOperationException: Unable to resolve service for type ‘Business.IDepartmentDetails’ while attempting to activate ‘POCAutomapperWithSql.Controllers.EmployeeController’.
- As we haven’t registered the interface in the container class (Program.cs). For registering the interface and classes, you need to go in the Program class (As Startup class is no more with .NET 6) and use these methods i.e. “AddScoped” || “AddTransient” || “AddSingleton” as it’s define the lifetime of the services.
STEP 5 — Go to Program class and register it.
To know more about the three methods which defines the lifetime of the service, Please follow the URL.
The source code for this template is on Github. Please feel free to come up with proposals to improve it.
I hope this article was helpful to you. Thanks for reading!
Happy learning! :)