When a controller creates every service it needs with new, it becomes responsible for building and managing the entire dependency chain. Inversion of Control (IoC) moves that responsibility out of the class and into a framework-managed component.
A simple example
Imagine an order controller needs an order service, and that service needs a database repository. Without IoC, the controller might construct both objects:
const repository = new OrderRepository();
const service = new OrderService(repository);
The controller now knows how the service and repository are created. If the repository changes, the controller may need to change too.
With IoC, the controller declares what it needs. NestJS creates and connects the objects through its IoC container.
How NestJS applies IoC
Nest uses a container to keep track of providers and their relationships. You register providers in modules, and Nest resolves their dependencies when it creates the application.
@Injectable()
export class OrderService {}
@Controller('orders')
export class OrderController {
constructor(private readonly orders: OrderService) {}
}
@Module({
controllers: [OrderController],
providers: [OrderService],
})
export class OrderModule {}
The controller does not call new OrderService(). It declares a dependency, and Nest supplies the instance.
Why is this useful?
- Less coupling: Classes do not need to know how their dependencies are constructed.
- Easier testing: A real service can be replaced with a fake or mock provider.
- Centralised lifecycle: Nest manages provider creation and reuse.
- Clearer boundaries: Modules describe which providers belong to a feature.
IoC is the broader design principle; dependency injection is one way to implement it. In NestJS, the container provides the IoC mechanism and DI is the everyday programming model built on top of it.
Remember: instead of your classes controlling the creation of everything they use, let the application container assemble the pieces.
Reference: NestJS Providers