Dependency Injection in ASP.NET Core Projects

Dependency Injection in ASP.NET Core Projects

Hi everyone. In this article i will try to explain what is the DI and How can you use it on ASP.NET Core projects. Also i will try to explain lifecycle types of Dependency Injection.

Dependency injection is a method used to minimize dependencies when applying SOLID principles. With the use of dependency injection, we have written appropriate code for the loosely coupled structure. When adding new features to the project, the cost of correction or addition is minimized.

While defining dependency, there are 3 different life cycles.

**Transient (AddTransient)
**It ensures that the object we create and use as dependency in the application is re-created for each use and call.

**Singleton (AddSingleton)
**It ensures that the object that we create and use dependency within the application is created one time and the same object is used within the application.

**Scoped (AddScoped)
**The dependency in the application allows the object we create to use the same object until the request ends, and a new object is created when it comes to a different call.

Using in ASP.NET Core Projects

I will talk about how I use it on an example I made on Github as an example of Redis. (https://github.com/okandavut/DotnetCoreRedisExample)

Image for post

You can see the project folder structure below. I will show you how I call a method I wrote in the Services layer with the dependency injection method from the Controller class.

The service I created uses the methods of the IBankingOperationsService interface. For the dependency injection method, you need to use the interface as I mentioned above.

Interface :

Image for post

Service:

Image for post

In the above code, there is simply a method that sends the list to the place where it is called.

After making these definitions, you need to define the method you will use while injecting this service method in Startup.cs. You have to do this for all dependencies.

I add the following code with the life cycle of Scoped type (until the request is ended).

Scoped : AddScoped, Transient : AddTransient, Singleton : AddSingleton

Image for post

With this addition, I can now use this service in my controller class with dependency injection method. For this :

Image for post

With this code, we define the object of the service we will use as private.

In the controller constructor method, after defining the service we will inject, we put the value on the contructor into the object we created privately. In this way, we can reach all the methods in the service with the least dependency.

We call the service method with the code below.

Image for post

As a result, Dependency Injection enables us to both minimize dependencies and manage them easily. :)

I tried to explain the Dependency Injection topic as simply as I could. Thank you for reading, sharing and applause will increase motivation :)