NestJS 中的依赖注入是如何工作的?

85 阅读1分钟

NestJS 使用依赖注入(DI)来管理组件之间的依赖关系。通过在类的构造函数中使用 @Injectable() 装饰器,可以将服务注入到控制器或其他服务中。例如:

typescript复制代码

import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  getData() {
    return 'Hello, World!';
  }
}

在控制器中注入服务:

typescript复制代码

import { Controller, Get } from '@nestjs/common';
import { MyService } from './my.service';

@Controller()
export class MyController {
  constructor(private readonly myService: MyService) {}

  @Get()
  getData() {
    return this.myService.getData();
  }
}

NestJS 的 DI 容器会在运行时自动实例化服务,并将其注入到需要的地方。