🦅 NestJS Beginner

What is Dependency Injection in NestJS?

Answer

Dependency Injection (DI) is a design pattern where a class receives its dependencies from an external source rather than creating them itself. NestJS has a built-in IoC (Inversion of Control) container that manages instantiation. When a class is decorated with @Injectable() and listed as a provider, NestJS registers it in the container. When another class declares it as a constructor parameter with type annotation, NestJS automatically creates and injects the correct instance. This decouples components, makes code testable (inject mocks in tests), and centralizes lifecycle management. The DI container is module-scoped — providers are only available within the module they are declared in (or exported).