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

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

typescript复制代码

typescript 复制代码
import { Injectable } from '@nestjs/common';

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

在控制器中注入服务:

typescript复制代码

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 容器会在运行时自动实例化服务,并将其注入到需要的地方。

相关推荐
我是苏苏1 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙1 小时前
Vue插槽
前端·vue.js
用户6387994773052 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT2 小时前
React + Ts eslint配置
前端
开始学java2 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat2 小时前
从零实现 React Native(2): 跨平台支持
前端·react native
狗哥哥2 小时前
🔥 Vue 3 项目深度优化之旅:从 787KB 到极致性能
前端·vue.js
青莲8432 小时前
RecyclerView 完全指南
android·前端·面试
青莲8432 小时前
Android WebView 混合开发完整指南
android·前端·面试
GIS之路2 小时前
GDAL 实现矢量数据转换处理(全)
前端