Dependency Injection – Session 16

Dependency Injection - Session 16 Feature Image

In this session of ASP.NET Core tutorial, we are going to talk about Dependency Injection in detail. This feature is a built-in capacity in ASP.NET Core that, enable us to improve our code testability, maintainability and empower our implementation.

How to inject dependency on Controller?

  • Step1: Create an Interface and determined required method
  • Step2: Create Implementation Class for created Interface
  • Step3: Add Interface and Implementation within ConfigureServices of Startup Class
  • Step4: Inject Interface to Controller via Constructor Injection

Dependency Injection and Controller

As you can see in the next image, CostController has dependency on ICostRepository that is injected to the Controller through Constructor Injection. Thus, ASP.NET Core create an instance from implementation of ICostRepository. But, ASP.NET Core cannot realize which implementation is required. Hence, we should register this service to ConfigureServices of Startup Class.

Controller Dependency Injection

Differences Between Add Service Methods

There are three different methods to add services to Web App. AddSingleton, AddTransient and AddScoped that their instance lifespans are different from each other.


This method creates an instance of the service once as per the request. Created instance is available in whole life of Web App and is the same in all the requests.


This method creates an instance of the service each time they are requested. Thus, the instance is always new in the different request. This method is suitable option for lightweight and stateless service.


This Method creates an instance of the service per each request. The instance is valid and same for whole the request but it is different in another request.

If you need more details, watch this session video. Also, for being updated about our coming sessions, follow us on Instagram, Facebook, Telegram or YouTube and you can have access to list of all sessions HERE.

You can download this Session Slides form HERE

0.00 avg. rating (0% score) - 0 votes


0 0 votes
Article Rating

Inline Feedbacks
View all comments