c# - ASP.NET Core MediatR 错误 : Register your handlers with the container

标签 c# asp.net-core autofac mediatr

我有一个 .NET Core 应用程序,在其中使用 .AddMediatR 扩展按照 CQRS 方法为我的命令和处理程序注册程序集。

在Startup.cs的ConfigureServices中,我使用了官方包MediatR.Extensions.Microsoft.DependencyInjection中的扩展方法,并带有以下参数:

services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);  

命令和命令处理程序类如下:

AddEducationCommand.cs

public class AddEducationCommand : IRequest<bool>
{
    [DataMember]
    public int UniversityId { get; set; }

    [DataMember]
    public int FacultyId { get; set; }

    [DataMember]
    public string Name { get; set; }
}

AddEducationCommandHandler.cs

public class AddEducationCommandHandler : IRequestHandler<AddEducationCommand, bool>
    {
        private readonly IUniversityRepository _repository;
        public AddEducationCommandHandler(IUniversityRepository repository)
        {
            _repository = repository;
        }

        public async Task<bool> Handle(AddEducationCommand command, CancellationToken cancellationToken)
        {
            var university = await _repository.GetAsync(command.UniversityId);

            university.Faculties
                .FirstOrDefault(f => f.Id == command.FacultyId)
                .CreateEducation(command.Name);

            return await _repository.UnitOfWork.SaveEntitiesAsync();
        }
    }

当我运行执行简单 await _mediator.Send(command); 代码的 REST 端点时,我从日志中收到以下错误:

Error constructing handler for request of type MediatR.IRequestHandler`2[UniversityService.Application.Commands.AddEducationCommand,System.Boolean]. Register your handlers withthe container. See the samples in GitHub for examples.

我试图查看文档中的官方示例,但没有任何运气。有谁知道我如何配置 MediatR 才能正常工作?

最佳答案

我也遇到了同样的问题。

问题是这行代码

services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);

处理所有 MediatR IRequest 和 IRequestHandler。

但是您创建了一个 IRepository 接口(interface)及其实现类,该接口(interface)无法由该 MediatR.Extensions.Microsoft.DependencyInjection

处理

因此保留所有更改,但添加此内容 - 手动注册此内容,例如

services.AddScoped(typeof(IUniversityRepository), typeof(UniversitySqlServerRepository));

然后问题就解决了。

关于c# - ASP.NET Core MediatR 错误 : Register your handlers with the container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50774060/

相关文章:

c# - 什么是学习来自 QBasic 和 VisualBasic 2008 的 Microsoft Visual C# 2008 的好资源?

c# - 如何以编程方式在 EA 中触发文档生成

c# - WCF:如何为类型中的类型构造 DataContract

c# - 堆栈跟踪优化

c# - 使用 Asp.NET Core 3.1 框架将文件上传到服务器时如何使用 IFormFile 作为属性?

c# - EF7 beta5 : Foreign Key returns null value

asp.net-core - 使用NLog记录请求正文和请求 header

autofac - 注册委托(delegate)时假定的 Autofac LifetimeScope 是什么?

c# - Autofac:如何加载引用但未直接使用的程序集

asp.net-mvc - Autofac 在具有混合 MVC 的 AppBuilder.Map block 中使用 Owin Web API 设置