NestJS模块化架构下依赖解析问题求助
NestJS多层模块依赖解析问题求助
问题背景
我是NestJS初学者,在模块化架构中碰到了依赖解析问题。简单模块依赖场景下一切正常,但多层依赖时出现注入失败的错误。
正常的简单依赖场景
Fs_So_Module导入FailureSoModule后,Fs_SoService可以正常注入FailureSoService:
@Module({ imports: [TypeOrmModule.forFeature([Fs_So]), FailureSoModule], controllers: [Fs_So_Controller], providers: [Fs_SoService], exports: [Fs_SoService], }) export class Fs_So_Module {}
@Injectable() export class Fs_SoService { constructor( @InjectRepository(Fs_So) private fs_SoRepository: Repository<Fs_So>, private failure_So_Service: FailureSoService, ) {} }
多层依赖下的错误场景
当SubOrderModule导入Fs_So_Module(Fs_So_Module本身依赖FailureSoModule),按Nest规则配置SubOrderModule后:
@Module({ imports: [ TypeOrmModule.forFeature([Sub_Order]), SetupSoModule, ImageSoModule, Fs_So_Module, ], controllers: [SubOrderController], providers: [SubOrderService], exports: [SubOrderService], }) export class SubOrderModule {}
SubOrderService注入Fs_SoService时抛出错误:
[Nest] 13844 - 13/03/2024, 10:46:04 ERROR [ExceptionHandler] Nest can't resolve dependencies of the SubOrderService (Sub_OrderRepository, SetupSoService, ImageSoService, ?). Please make sure that the argument Fs_SoService at index [3] is available in the SubOrderModule context.
临时解决方案(不理解原理)
我找到了一个临时解决办法,但不清楚为什么需要同时导入模块、TypeOrmModule并声明服务:
@Module({ imports: [ TypeOrmModule.forFeature([Sub_Order, Fs_So, Failure_so]), SetupSoModule, ImageSoModule, Fs_So_Module, FailureSoModule, ], controllers: [SubOrderController], providers: [SubOrderService, Fs_SoService, FailureSoService], exports: [SubOrderService], }) export class SubOrderModule {}
求助需求
已确认AppModule中的模块导入正常,希望有人解释问题原因并提供正确的解决方法。
内容的提问来源于stack exchange,提问作者Matthieu Dantes
相关产品推荐
相关产品推荐

