gpt4 book ai didi

c# - ASP.NET Core MediatR 错误 : Register your handlers with the container

转载 作者:行者123 更新时间:2023-12-01 16:12:52 32 4
gpt4 key购买 nike

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

最佳答案

我也遇到了同样的问题。

问题是这行代码

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

处理所有 MediatR IRequest 和 IRequestHandler。

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

处理

因此保留所有更改,但添加此内容 - 手动注册此内容,例如

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

然后问题就解决了。

关于c# - ASP.NET Core MediatR 错误 : Register your handlers with the container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50774060/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com