Dependency Injection

Tak Yu Chan (Franky)
2 min readApr 8, 2021
Photo by Sam Moqadam on Unsplash

Intention

Dependency Injection helps us to be loosely coupled application by injecting the dependencies by the client instead of hard coded the instance (class).

It also make the application testable as we can create mock class that implements the same interface for testing.

class WithoutDI {  val chief = John() // chief has to be John}class WithDI(val IChief) { // chief can be anyone that is a chief (does not need to be IChief, but an interface of a behaviour)
}

There are two types of Dependency Injection, manual DI and auto DI, and below focuses on auto DI which make developers life easier.

Advantages

  • Improved testability
  • Single source for managing dependencies (Maintainable)
  • Easy to change dependencies

Using .NET CORE as an example

The DI is baked right into the heart of .NET Core for us to utilize it.

  • Register the service (dependency) in the service container, in .net core we put them into Configure Services.
  • To register the service, we need to specify the interface and the concrete class (implementation).

And the service container will serve up to inject the concrete class we have associated with the interface (dependency) in its place.

Then if we need to swap out the concrete class for other implementation, we only need to make the change in one place (Service Container).

Make use of the dependency

One of the ways to use the dependency is Constructor Dependency Injection.

--

--