Modules and Dependency Injection

Explore modules, DI, providers, and provider scopes in depth.

Understanding modules and DI

At the heart of NestJS are two fundamental concepts: modules and DI. They are crucial in structuring and keeping our application organized as it grows. Modules act as containers for organizing and encapsulating code. DI is a design pattern that NestJS embraces fully. It simplifies managing dependencies and makes our code more testable and modular.

In this lesson, we’ll explore these two concepts in detail and see how they’re applied in practice.

Modules

NestJS follows a modular architecture. The modular architecture means the code is organized into small, self-contained modules. Each module acts like a building block, with each responsible for a different task.

Every app contains at least one root module as the entry point of the app. In NestJS, this is often the AppModule module by convention. We can add more feature modules to separate the functionalities when the app grows. Using modules makes the app easier to understand and maintain.

In NestJS, the module is a class decorated by the @Module decorator. Within the module class, we can register the controllers, services, and other modules on which the module depends. The following is a basic example of a module class:

Get hands-on with 1200+ tech skills courses.