NestJS中如何向函数表达式类型的handler注入类提供者ConfigService
方案1:导出应用实例直接获取服务(改动量最小)
只需要修改main.ts加个导出,再在handler里加3行以内的代码即可:
- 修改
main.ts,暴露应用实例的获取方法:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { INestApplication } from '@nestjs/common'; let app: INestApplication; // 新增导出方法 export const getNestApp = () => app; async function bootstrap() { app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
- 在handler文件中直接获取ConfigService实例:
import { getNestApp } from '../main'; import { ConfigService } from '../config/config.service'; export const handler = async (args) => { const configService = getNestApp().get(ConfigService); // 直接使用configService的方法即可,比如configService.get('DB_HOST') }
方案2:复用现有HandlersModule存储服务实例(无全局暴露)
利用当前没有实际作用的handlers.module.ts存储ConfigService实例,不需要暴露全局应用:
- 修改
handlers.module.ts:
import { Module, OnModuleInit } from '@nestjs/common'; import { ConfigModule } from '../config/config.module'; import { ConfigService } from '../config/config.service'; // 导出模块级别的ConfigService变量 export let configService: ConfigService; @Module({ imports: [ConfigModule] }) export class HandlersModule implements OnModuleInit { constructor(private injectConfigService: ConfigService) {} onModuleInit() { // 模块初始化完成后给外部变量赋值 configService = this.injectConfigService; } }
- 把
HandlersModule导入到根模块AppModule的imports数组中,确保模块被Nest加载。 - 在handler文件中直接使用导出的configService:
import { configService } from './handlers.module'; export const handler = async (args) => { // 直接使用configService即可 }
注意事项
- 保证handler执行时机在Nest应用初始化完成之后即可,避免实例未赋值导致undefined。如果有提前执行的场景,可给获取实例的逻辑加简单的轮询等待判断。
- 两种方案都完全保留handler的函数导出形式,不会影响
producer.ts的读取逻辑。
内容的提问来源于stack exchange,提问作者Kartik Chauhan
相关产品推荐
相关产品推荐

