Skip to content

Dependency injection

Devrath edited this page Sep 29, 2023 · 6 revisions

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
Clone this wiki locally