What is dependency injection?

Ceren Susuz
2 min readMar 7, 2023

--

Inversion of Control (IoC) design principle is defined as given responsiblity for control or logic to something else such as a framework.

Dependency Injection (DI) is a design pattern that is part of the IoC design pattern allows dependent objects of a class to be created elsewhere rather than in the class itself.

ASP.NET Core has a built in DI container and is designed to support dependency injection. The way it works that you register the classes as services in your application. There services are registered as part of your web application’s DI container as a service descriptor instance. Each registered service is added as a collection to an IServiceCollection instance.

Once the application has started, these services can be resolved using an IServiceProvider instance. This instance looks at the registered service to resolve them at runtime.

Service Lifetimes

  • Singleton : only created once per application. Once it’s been created the instance will be alive until the service is disposed of when the application stops.
  • Scoped : are initilized when a scope is created. The instance will be alive until the scope has been disposed of. A scope is either defined for a life cycle of a HTTP request, or it can be explicitly defined.
  • Transient: have new instances every time they’re requested. This means that these instances cannot be shared in different components of the application. They are ideal for retriving information from a db or an API.

--

--

Ceren Susuz
Ceren Susuz

Written by Ceren Susuz

Software Developer at EMakina an EPAM Company

No responses yet