我有一个 .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 错误:向容器注册您的处理程序
发布评论