:::: MENU ::::

Dependency Injection in ASP.NET CORE

First let’s know about what is Dependency Injection and why we need this.

Dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. DI is widely adopted because this technique helps developer for achieving loose coupling between objects and its collaborators, or dependencies. Rather than directly instantiating collaborators, or using static references, the objects a class needs in order to perform its actions are provided to the class in some fashion. Mostly there are three common approach to achieve DI Setter, Interface, and Constructor. [Wikipedia]

To provide required dependency for the classes there will be other classes ready with those services which are called as Inversion of Control (IoC) Containers or Dependency Injection (DI) containers. A container is essentially a factory that is responsible for providing instances of types that are requested from it. If a given type has declared that it has dependencies, and the container has been configured to provide the dependency types, it will create the dependencies as part of creating the requested instance.

ASP.NET Core now ship with built-in support for Dependency Injection. It provide simple built-in container that support constructor injection by default but you can use any other IoC provider like AutoFac, DryIoc etc. You can configure the built-in container’s services in the ConfigureServices method in your application’s startup class. ConfigureServices method is responsible for defining the services the application will use and services could be framework provided services or your own custom services.

Let’s understand this by example. For this example lets create an interface and class that implement interface then register service and access service form your application. We will use postal code service for this example which return appropriate postal code as per provided district name.

Let’s create interface with name IPostalCodeService which contains GetPostalCode method which take district name as a parameter and lets implement this interface to our class.

Now our interface and its implemented class is ready let’s register our awesome PostalCodeService with DI container so we can inject this service anywhere we need it in our application. Like AddTransient there are other methods available which has different purpose and we will discuss it later. Here we are passing interface and its implemented class service as type parameter for method. Actually this method maps the interface and concrete class which means any time this service (interface) is injected then it provides instance of the mapped class. Now register your service in DI container in ConfigureServices method of startup.cs class.

So we registered our services it means now you can inject it from any where inside your application. Here we are injecting service from DistrictController constructor and use that service in GET action. In MVC project you can inject this dependency in view files too. [we are using web API project for this sample.]

Note: All services that you registered are fall under RequestServices container so you can have access on those services using HttpContext property.

But its not good practice to inject dependency using RequestServices anywhere you need. Always prefer to inject dependency via class’s constructor so you can have more loosely coupled classes and also it helps making your test easier for that class.

If you have to register multiple services on DI container then you better use extension methods to keep you ConfigureServices method simple.

There is naming convention for extension methods in ConfigureServices method i.e. AddServices where add should be in front followed by generic/specific type of services name.

Let’s talk about Service registration options and their life time:

It is important to choose an appropriate lifetime for each of the services you register. Should a new instance of the service be provided to each class that requests it? Should one instance be used throughout a given web request? Or should a single instance be used for the lifetime of the application?

Available service registration options are:

– Transient

Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services.

-Scoped

Scoped lifetime services are created once per request.

-Singleton

Singleton lifetime services are created the first time they are requested and then every subsequent request will use the same instance.

If you want to know more about lifetime of the object created by using one of these methods with example then visit official docs.

In conclusion, this is what dependency injection and how you can implement Dependency injection in ASP.NET Core.

Quick Note: Don’t mix your DI services with static object access approach In Fact DI is alternative to static/global object access pattern. With the help of DI your application can be more clean, lightweight, maintainable and testable.

Happy Coding 🙂