我有一个.Net Core应用程序,在其中我使用 .AddMediatR 扩展名按照CQRS方法为我的命令和处理程序注册程序集.
I have a .Net Core app where i use the .AddMediatR extension to register the assembly for my commands and handlers following a CQRS approach.
在Startup.cs的ConfigureServices中,我使用了官方包 MediatR.Extensions.Microsoft.DependencyInjection 中的扩展方法,并带有以下参数:
In ConfigureServices in Startup.cs i have used the extension method from the official package MediatR.Extensions.Microsoft.DependencyInjection with the following parameter:
services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);命令和命令处理程序类如下:
The command and commandhandler classes are as follow:
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端点时,我从日志中得到以下错误:
When i run the REST endpoint that executes a simple await _mediator.Send(command); code, i get the following error from my log:
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使其正常工作?预先感谢.
I tried to look through the official examples from the docs without any luck. Does anyone know how i configure MediatR to work properly? Thanks in advance.
推荐答案我遇到了同样的问题.
问题是此行代码
services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);
处理所有MediatR IRequest和IRequestHandlers.
handles all the MediatR IRequest and IRequestHandlers.
但是您创建了一个IRepository接口及其实现类,该接口无法由该 MediatR.Extensions.Microsoft.DependencyInjection
but you created an IRepository interface and its implementation class which can't be handled by that MediatR.Extensions.Microsoft.DependencyInjection
因此请保留所有更改,但要添加它-像
so keep all your changes but add this - manually register this like
services.AddScoped(typeof(IUniversityRepository),typeof(UniversitySqlServerRepository));
然后问题解决了.
更多推荐
ASP.NET Core MediatR错误:向容器注册处理程序
发布评论