我有一个 .Net Core 应用程序,我使用.AddMediatR扩展程序按照 CQRS 方法为我的命令和处理程序注册程序集。
在 Startup.cs 的 ConfigureServices 中,我使用了官方包中的扩展方法,并MediatR.Extensions.Microsoft.DependencyInjection带有以下参数:
services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);
命令和命令处理程序类如下:
添加教育命令.cs
public class AddEducationCommand : IRequest<bool>
{
[DataMember]
public int UniversityId { get; set; }
[DataMember]
public int FacultyId { get; set; }
[DataMember]
public string Name { get; set; }
}
添加EducationCommandHandler.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 才能正常工作?提前致谢。