DEV Community

Cover image for Understand Dependency Injection in NestJs in a simple way
João Paulo
João Paulo

Posted on

Understand Dependency Injection in NestJs in a simple way

Dependency injection is when an object provides the dependency of another object. This means that a class relies on methods from another class. It is a well-known design pattern, and Nest is built strongly based on this pattern.

Inversion of control is a concept that aligns with dependency injection. It is basically delegating to the framework the construction of the project's dependencies.

The purpose of injection is to invert control, providing the dependencies of the object instead of allowing it to create them itself. For this, it is necessary to:

  1. Explicitly define the dependencies and where the injection occurs. In Nest, for example, this point is in the constructor. This is where the framework inverts control. constructor(private catsService: CatsService) {}
  2. Have an inversion of control container for dependency injection to occur. In Nest, it is possible to access this container through the module and retrieve the instance of the class we want.

In short, what is done is transferring the task of instantiating the object to someone else (IoC) and directly using that instance as a dependency (Injection).

Advantages of using this pattern:

  • Ease of testing the application (we can inject mocked services)
  • Improved code maintenance (reduction of code and decoupling)
  • Reusability (just inject the dependency to use it)

Disadvantages: There are few, but generally:

  • Increased complexity in the project
  • Service construction logic can be in inaccessible places

Thank you for reaching this point. If you need to contact me, here is my email: joaopauloj405@gmail.com

References:
https://www.digitalocean.com/community/tutorials/a-guide-on-dependency-injection-in-nestjs
https://martinfowler.com/articles/injection.html
https://www.youtube.com/watch?v=GX8YC21qQQk&t=1010s

Top comments (0)