How does dependency injection work?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn Dependency injection
Definition:
Dependency injection means a class receives the objects it needs instead of constructing them itself. Nest's container uses registered provider tokens to build and connect these dependencies. This centralizes construction and lets tests or configuration replace an implementation without rewriting its consumers.
Key points:
-
A class asks for a dependency in its constructor.
-
Nest finds its provider token and supplies the registered instance.
-
This makes dependencies easier to replace in tests.
-
The
@Injectabledecorator supplies metadata, but the provider must also be available through the module graph.
Example:
import { Injectable, Module } from '@nestjs/common';
@Injectable()
class TaxService {
calculate(amount: number) { return amount * 0.1; }
}
@Injectable()
class OrderService {
constructor(private readonly tax: TaxService) {}
total(amount: number) { return amount + this.tax.calculate(amount); }
}
@Module({ providers: [TaxService, OrderService], exports: [OrderService] })
class OrderModule {}- Nest constructs the registered services and supplies
TaxServicetoOrderService. - The arithmetic is only a DI example; real money calculations need exact units and rounding rules.
Interview point:
- Explain construction and replacement with a service/repository example rather than defining DI only as “using a constructor.”
Adapted from 03_NESTJS.md · “How does dependency injection work?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.