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

问题描述 投票:7回答:2

我有一个.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正常工作?提前致谢。

asp.net-core autofac mediatr
2个回答
9
投票

我遇到了同样的问题。

问题是这个行代码

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

处理所有MediatR IRequest和IRequestHandlers。

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

所以保留所有的更改,但添加这个 - 手动注册这样

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

然后问题解决了。


0
投票

我有同样的问题,在我的情况下,当我在调用services.AddMediatR()之后注册某些处理程序所需的依赖项是实际问题时,在我开始注册我的依赖项之前注册Mediator一切正常。

我使用dot net core 2.2和默认的DI容器和MediatR 6.0.0。

© www.soinside.com 2019 - 2024. All rights reserved.