Dependency Injection in ASP .NET core (Singleton, Transit, Scoped)

Maulik Patel
2 min readOct 14, 2022

--

We all used dependency injection for decoupled application and constructor injection of services.

As we know our implementation should be used interface or base abstract classes to decoupled architecture. It’s avoid hardcoded dependency on concreate classes which help to achieve DI and inject dependency with constructor.

.NET core support Dependency Injection (DI) software design pattern, which is a technique for achieving inversion of control (IOC) between classes and their dependency.

.NET core provide inbuilt framework for DI. Some external library like AutoFact, Ninjact used for DI which support property injection.

Dependency injection address below problems:

  1. The use of an interface or base class to abstract the dependency implementation.
  2. Registration of the dependency in a service container. .NET provides a built-in service container, IServiceProvider.
  3. Injection of the service into the constructor of the class where it’s used. The framework takes on the responsibility of creating an instance of the dependency and disposing of it when it’s no longer needed.

Service lifetimes

Transient

Transient lifetime created each time there are requested from service container. This works for lightweight, stateless services. Transient services are disposed at the end of request.

Scoped

A scoped lifetime indicates that services are created once per client request (connection).Scoped services are disposed at the end of the request. When using Entity Framework Core, the AddDbContext extension method registers DbContext types with a scoped lifetime by default.

Singleton

Singleton lifetime services are created when first time they’re requested. Every subsequent request used same instance from container service. Singleton services are disposed when the service provider is disposed on application shutdown. Because memory is not released until the app is shut down. Consider memory use with singleton service.

For example logging and caching services mark as singleton services. We should be little caution as it is shared object for all requests.

Let’s see below console screen for understanding instance on each service lifetime.

VehicleApplication class registered as transit so it’s instance would be created on each time when requested.

VehicleRepostiory class registered as scoped so It’s instance remains same for same call as we can see call 1 has same guid. So it change on different request but remain same for single request scope.

Myservice class registered as singleton so it’s instance will be created only once. We can see same guid for both request and calls in console screen.

Thanks for reading!!!

--

--

Maulik Patel

Full stack Software Engineer. C# | .NET core | MSSQL | Azure | Docker | Angular12+