Dependency Injection and Service Lifetimes in .NET Core

  • Removes hardcoded dependencies and allows them to be changed
  • Allows the developer to write loosely coupled code, making applications easier to maintain, extend, and test
  • Increase the testability in software applications that use DI. Loosely coupled code can be tested more easily. It’s easier to make a change in the code without affecting other areas of the application. With DI it’s possible to inject mocked dependencies in the tests.
  • Developers can work on different pieces of functionality in parallel since the implementations are independent of each other.
  • Improve the readability and cleanliness of the code
  • Transient — Services are created each time they are requested. It gets a new instance of the injected object, on each request of this object. For each time you inject this object is injected in the class, it will create a new instance.
  • Scoped — Services are created on each request (once per request). This is most recommended for WEB applications. So for example, if during a request you use the same dependency injection, in many places, you will use the same instance of that object, it will make reference to the same memory allocation.
  • Singleton — Services are created once for the lifetime of the application. It uses the same instance for the whole application.
  • The two Transient objects have two different values. It hits the constructor of ExampleTransientService class twice, once for each call.
  • The two Scoped objects have the same values. It hits hit the constructor of ExampleScopedService class only once, because the request is the same.
  • The two Singleton objects have the same values. It hits the constructor of ExampleSingletonService class only once.
  • The two Transient objects again have two different values. It hits the constructor of ExampleTransientService class twice, once for each call.
  • Both Scoped objects have the same value. It hits hit the constructor of ExampleScopedService class only once, because the request is the same.
  • The two Singleton objects have the same values from the first time when the application runs. This second time when the page was refreshed, the did not hit the constructor of the ExampleSingletonService class, and it will not hit the constructor again unless the application is restarted.
https://github.com/henriquesd/DependencyInjectionAndServiceLifetimes

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store