NestJS中MongooseModule钩子注入第三方服务失败问题求助
问题分析与解决方案
你的代码存在循环依赖问题:在MongooseModule.forFeatureAsync的配置里,你导入了SharedModule本身,而SharedModule正在定义中,导致模块无法正常加载。同时,MyService需要被导出才能让CommandeModel的依赖注入正常工作。
修复步骤
1. 移除循环依赖
删除MongooseModule.forFeatureAsync配置中的imports: [SharedModule],因为当前模块已经声明了MyService作为provider,无需自己导入自己。
2. 保留MyService的导出
必须保留exports: [MyService],这样Nest才能在创建CommandeModel时解析到MyService的依赖。
修改后的代码
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { Commande, CommandeSchema } from 'src/commande/commande.model'; import { MyService } from './my.service'; // 确保正确导入MyService @Module({ imports: [ MongooseModule.forFeatureAsync([ { name: 'Commande', // 移除了导致循环依赖的imports配置 inject: [MyService], useFactory: async (myService: MyService) => { const schema = CommandeSchema; schema.post('save', async function (doc) { const commande = doc as unknown as Commande; await myService.savingLivraison(commande); }); return schema; }, }, ]), ], providers: [MyService], exports: [MyService, MongooseModule] // 可选:如果其他模块需要使用CommandeModel,也导出MongooseModule }) export class SharedModule { }
额外建议(可选)
如果SharedModule承载了过多功能,建议将MyService拆分到独立的MyServiceModule中,再在SharedModule里导入该模块,这样能进一步避免依赖混乱:
// my-service.module.ts import { Module } from '@nestjs/common'; import { MyService } from './my.service'; @Module({ providers: [MyService], exports: [MyService] }) export class MyServiceModule { }
然后修改SharedModule:
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { Commande, CommandeSchema } from 'src/commande/commande.model'; import { MyServiceModule } from './my-service.module'; @Module({ imports: [ MyServiceModule, MongooseModule.forFeatureAsync([ { name: 'Commande', inject: [MyService], useFactory: async (myService: MyService) => { const schema = CommandeSchema; schema.post('save', async function (doc) { const commande = doc as unknown as Commande; await myService.savingLivraison(commande); }); return schema; }, }, ]), ], exports: [MyServiceModule, MongooseModule] }) export class SharedModule { }
这样结构更清晰,也彻底避免了循环依赖的风险。
内容的提问来源于stack exchange,提问作者Raymond SADIO
相关产品推荐
相关产品推荐

