NestJS
NestJS 架构解密:IoC 控制反转与 DI 依赖注入容器底层实现
Waitwalker2026-08-2015 min
## 1. 为什么 NestJS 引入 IoC 控制反转?
在传统 Node.js 服务端开发中,类与类之间往往直接通过 `new Service()` 紧密耦合,导致单元测试困难、模块难以替换。
NestJS 引入了 **IoC (Inversion of Control)** 与 **DI (Dependency Injection)**:
- 对象的生命周期和装配逻辑交由 Nest 运行时容器统一管理。
- 类只需声明依赖,无需关心依赖如何被实例化。
```typescript
@Injectable()
export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
}
@Controller("users")
export class UsersController {
constructor(private readonly usersService: UsersService) {}
}
```
## 2. reflect-metadata 与设计期类型提取
NestJS 通过 `emitDecoratorMetadata: true` 编译选项,在运行时借助 `Reflect.getMetadata("design:paramtypes", target)` 自动捕获构造函数入参的真实类型,进而实现全自动化的依赖注入。
#NestJS#IoC/DI#TypeScript#后端架构
回到文章列表 →