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

相关推荐
swipe1 天前
为什么 RAG 一定离不开向量检索:从文档向量化到语义搜索的工程实现
前端·llm·agent
OpenTiny社区1 天前
AI-Extension:让 AI 真的「看得到、动得了」你的浏览器
前端·ai编程·mcp
IT_陈寒1 天前
Redis缓存击穿:3个鲜为人知的防御策略,90%开发者都忽略了!
前端·人工智能·后端
农夫山泉不太甜1 天前
Tauri v2 实战代码示例
前端
yuhaiqiang1 天前
被 AI 忽悠后,开始怀念搜索引擎了?
前端·后端·面试
红色石头本尊1 天前
1-umi-前端工程化搭建
前端
真夜1 天前
关于对echart盒子设置百分比读取的宽高没有撑开盒子解决方案
前端
楠木6851 天前
RAG 资料库 Demo 完整开发流程
前端·ai编程
肠胃炎1 天前
挂载方式部署项目
服务器·前端·nginx
像我这样帅的人丶你还1 天前
使用 Next.js + Prisma + MySQL 开发全栈项目
前端