Skip to content

Dependency injection

Devrath edited this page Oct 10, 2023 · 6 revisions

dependency-injection

Dependency injection compared with the traditional way of retrieving the dependencies

Untitled Diagram drawio

What is Constructor injection

  • Every class has a responsibility to perform some functionality.
  • Sometimes in order to perform the desired behavior, we will need other dependencies from other sources(classes, modules, fields).
  • One way is to build the objects inside the class itself and use them. This is not preferred since the type becomes harder to test and the single responsibility principle is not met.
  • A better approach is to inject the class with the abstraction of the functionality. This will lead to preserving a single responsibility and also, the class is easily testable since we can mock the dependencies injected and test the current class.
  • Also we create an object by calling the constructor, If the class expects all the dependencies as parameters, Then we can be sure that a class will never be instantiated without all the dependencies it requires

What is Field injection

  • We use field injection in scenarios where we cannot use the constructor injection.
  • There specific scenarios where for example in android framework classes like activities where framework instantiates the class since we cannot access the constructor of the framework class and in such scenarios we use field injection.

Dependency Injection: with SOLID principles

With the help of DI, helps to create modules that are loosely coupled. Basically DI helps in achieving 2 important SOLID principles

  • Single Responsibility ➑️ Each class has only one reason to change, If there is more than one reason to change then it violates the single responsibility principle
  • Dependency Inversion ➑️ Upper-level modules cannot depend on the lower-level modules. Basically, you should always plug the upper-level to lower-level modules so that the lower level can access the upper-level modules but not vice-versa.
Clone this wiki locally