Dependency injection in ASP.NET Core

  • To replace SomeService with a different implementation, the ViewModelService class must be modified.
  • If SomeService has dependencies, they must also be configured by the ViewModelService class. In a large project with multiple classes depending on SomeService, the configuration code becomes scattered across the app.
  • This implementation is difficult to unit test. The app should use a mock or stub SomeService class, which isn't possible with this approach.
  • The use of an interface or base class to abstract the dependency implementation.
  • Registration of the dependency in a service container. ASP.NET Core provides a built-in service container, IServiceProvider. Services are typically registered in the app’s Startup.ConfigureServices method.
  • 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.
  • Doesn’t use the concrete type SomeService, only the ISomeService interface it implements. That makes it easy to change the implementation that the ViewModelService class uses without modifying the it.
  • Doesn’t create an instance of SomeService, it's created by the DI container.

Service lifetimes

  • Transient
  • Scoped
  • Singleton

Transient

Scoped

Singleton

Let’s play more on DI

--

--

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