DEV Community

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

Posted on

6 1 1 1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay