You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS无法解析CommandHandler依赖问题求助

Nest.js CQRS依赖注入错误:EventPublisher无法解析

错误信息

Nest can't resolve dependencies of the ReceiveChatLineCommandHandler (?, Repository). Please make sure that the argument EventPublisher at index [0] is available in the SmershModule context.

问题场景

控制器的依赖注入正常工作,但命令处理程序的依赖注入失败。尝试过在app.module.ts中导入CqrsModule,也尝试过单独导入单个命令处理程序,但都无效。

相关代码片段

smersh.module.ts

@Module({
    imports: [CqrsModule<Event>],
    controllers: [
        LandingPageController,
        CurrentStatusController,
        CurrentChatController,
        PlayersController,
        PlayerController,
        CondemnPlayerController,
        LayoutController
    ],
    providers: [
        Repository,
       ...CommandHandlers,
       ...EventHandlers
    ]
})
export class SmershModule implements OnModuleInit {
    public log : FileLogger

    public onModuleInit(): void {
        this.log = new FileLogger(`./info-${new Date().toISOString().split('T')[0]}-${this.constructor.name}.log`)
        this.log.info('smersh module initiated', this)
    }
}

app.module.ts

@Module({
    imports: [SmershModule],
})
export class AppModule {

}

ReceiveChatLineCommandHandler.ts

@CommandHandler(ReceiveChatLineCommand)
export class ReceiveChatLineCommandHandler implements ICommandHandler<ReceiveChatLineCommand> {
    constructor(
        protected readonly publisher: EventPublisher,
        protected readonly repository: Repository
    ) {
    }

    async execute(command : ReceiveChatLineCommand) {
        const { Id, Line, Date } = command
        const domain = this.publisher.mergeObjectContext(await this.repository.Get<RoundSearchReport, Round>(Id))
        domain.receiveChatLine(Line, Date)
        domain.commit();

    }
}

index.ts

import { ReceiveChatLineCommandHandler } from './Round'

export const CommandHandlers =  [
    ReceiveChatLineCommandHandler
]

解决方案

问题根源在于**CqrsModule的导入方式错误**:

  1. 你当前使用的CqrsModule<Event>写法不符合Nest.js CQRS模块的初始化规范,直接导入模块类不会注册CQRS核心依赖(包括EventPublisher)。

  2. 修正SmershModule中的导入代码,使用CqrsModule.forRoot()方法初始化模块:

@Module({
    imports: [CqrsModule.forRoot()], // 替换原有的CqrsModule<Event>
    controllers: [/* 保持原控制器列表 */],
    providers: [/* 保持原提供者列表 */]
})
export class SmershModule implements OnModuleInit {
    // ... 其他代码不变
}
  1. 确保已正确安装@nestjs/cqrs依赖包:
npm install @nestjs/cqrs
# 或
yarn add @nestjs/cqrs

CqrsModule.forRoot()会自动注册CQRS所需的所有核心提供者,包括EventPublisher,这样Nest就能正确解析命令处理程序中的依赖注入。


内容的提问来源于stack exchange,提问作者Schmock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:01:35