ASP.NET Core MediatR错误:使用容器注册您的处理程序

47

我有一个.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以正常工作吗?


1
问题之外还有很多可能出错的地方。请提供“最小完整可验证示例”(MCVE),这样我们才能了解您在做什么。 (注:链接为 https://stackoverflow.com/help/mcve ) - Alexander Leonov
你应该前往 https://github.com/jbogard/MediatR/blob/master/samples/MediatR.Examples.AspNetCore/Program.cs,因为还有很多代码需要编写来注册 MediatR 及其处理程序。 - hugo
7
附加调试器并检查InnerException。 可能是IUniversityRepository没有注册,因此无法构建RequestHandler。 services.AddMediatR()不足够,您还需要在服务集合中注册所有其他依赖项。 - PeterFromCologne
谢谢Peter,我的Autofac模块配置中存储库的配置有问题。 - Mike Hawkins
17个回答

0

我忘记在我的处理程序类中添加IRquestHandler<>

public class AddChildCategoriesToPOSHandler : IRequestHandler<AddChildCategoriesToPOSCommand>

0

我在.NET Core Web API中使用CQRS模式时遇到了同样的问题。我错误地将处理程序定义为internal而不是public。请确保将处理程序定义为public类。


0

https://github.com/LeftTwixWand/ModernCQRS

这里我展示如何通过 DI 容器(Autofac)注册最新的 MediatR 版本

另外,我添加了 CQRS 的命令/查询

还添加了请求装饰器和 MediatR 管道:

enter image description here


0

我知道你没有使用ILogger,但如果有人使用它遇到了这个问题,对于我的情况,ILogger是问题所在。

我的QueryHandler代码如下:

public class GetNearbyChargeBoxesQueryHandler : IRequestHandler<GetNearbyChargeBoxesQuery, Response<IEnumerable<GetNearbyChargeBoxesViewModel>>>
        {
            private readonly ILogger _logger;
            private readonly IChargeBoxRepositoryAsync _chargeBoxRepository;
            private readonly IMapper _mapper;

            public GetNearbyChargeBoxesQueryHandler(ILogger logger, IChargeBoxRepositoryAsync chargeBoxRepository, IMapper mapper)
            {
                _logger = logger;
                _chargeBoxRepository = chargeBoxRepository;
                _mapper = mapper;
            }

.....
....
..
.


当我深入调试时,我注意到ILogger出了问题,然后我使用了像这样的ILogger _logger;而不是ILogger _logger;
看起来很荒谬,但这解决了我的Error constructing handler for request of type MediatR.IRequestHandler.......
错误。

0
在我的情况下,我忘记在启动时注册某些内容。例如,我试图通过控制器实现的存储库。这在Startup.cs文件的ConfigureServices方法中缺失:
 services.AddScoped<IDemoRepository, DemoRepository>();

0
在我的情况下,堆栈跟踪显示了问题发生的原因:
System.InvalidOperationException: Error constructing handler for request of type    

MediatR.IRequestHandler`2[XXX.Core.Auth.Refresh.Request,XXXX.Core.Auth.Response]. 

Register your handlers with the container. See the samples in GitHub for examples.

---> MySqlConnector.MySqlException (0x80004005): Access denied for user 'sqluser'@'localhost' (using password: YES)

我的数据库中没有在连接字符串中指定的用户设置。通过将该用户添加到数据库中进行修复。


-1
你需要注入中介者的依赖项,使用 .Net 6 我可以通过在 Program.cs 中使用以下代码来解决这个问题:
builder.Services.AddMediatR(typeof(Program).Assembly);
builder.Services.AddScoped<IRequestHandler<CreateProductCommand, Unit>, CreateProductCommandHandler>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接