【问题标题】:MediatR usage in DDD with handler not found error未找到处理程序错误的 DDD 中的 MediatR 使用
【发布时间】:2020-10-20 11:43:52
【问题描述】:

我正在学习 CQRS 并在 DDD 项目中实施 MediatR。 我有以下项目结构:

Domain
    - Commands
        - Requests
        - Handlers
    - Models
    - Interfaces
        - Repositories

CrossCutting
    NativeInjectionBootstrapper.cs

Presentation
    - Controllers

因此,在 Presentation Project 中,我使用 NativeInjectionBootstrapper.cs 注入了所有存储库和其他依赖项,并在 Startup.cs 中添加了 services.AddMediatR(typeof(Startup))

Domain > Commands > Request 中,我实现了IRequest<> 接口。

Domain > Commands > Handlers 中,我实现了IRequestHandler<> 接口。

接口注入成功,但是当请求控制器时我收到以下错误:

System.InvalidOperationException: 
Handler was not found for request of type MediatR.IRequestHandler`2 [Domain.Commands.Requests.Product.NewProductRequest,System.String]. 
Register your handlers with the container. 
See the samples in GitHub for examples.

我在这里寻求帮助,有人建议在启动时添加另一种类型的 MediatR,例如 services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);,但我没有成功。

我正在搜索如何注册处理程序,但我找不到任何东西。

【问题讨论】:

  • 当我只使用一个项目时,一切正常,但是当我分成项目时,我得到了错误。

标签: asp.net-core-webapi mediatr


【解决方案1】:

我尝试在services.AddMediatR() 中添加域项目程序集,并且成功了。

像这样:

services.AddMediatR(
     AppDomain.CurrentDomain.Load("Buzzy.Presentation"), 
     AppDomain.CurrentDomain.Load("Buzzy.Domain")
);

我不知道这是否正确,但有效。

【讨论】:

    【解决方案2】:

    您需要在定义处理程序的程序集中注册 MediatR:

    services.AddMediatR(typeof(AddEducationCommandHandler).Assembly);
    

    您是否阅读过文档:https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 2020-12-08
      • 2020-03-14
      • 2020-01-24
      • 2021-01-19
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多