我正在构建应用程序并尝试使用 MediatR 实现域事件。我在使用 MediatR 4.0.0 的 .NET Core 2.1(预览版,但我认为这不是问题)
我正在使用 eShopOnContainers/Ordering 服务的示例。他们使用 Autofac,但我更愿意坚持使用使用MediatR 扩展的本机 DI 容器
我的应用程序在启动时崩溃了。错误:
System.ArgumentException: '无法为服务类型实例化实现类型'MyProject.API.Application.Commands.IdentifierCommandHandler`2[T,R]'
'MediatR.IRequestHandler
2[MyProject.API.Application.Commands.IdentifiedCommand
> 2[T,R],R]'。
我的 Nuget 包:
<ItemGroup>
<PackageReference Include="MediatR" Version="4.0.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="4.0.0" />
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0-preview1-final" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0-preview1-final" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.1.0-preview1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="2.2.0" />
</ItemGroup>
尝试注册 IdentifiedCommandHandler 时,我的应用程序在启动时崩溃:
public class IdentifiedCommandHandler<T, R> : IRequestHandler<IdentifiedCommand<T, R>, R>
where T : IRequest<R>
{
private readonly IMediator _mediator;
private readonly IRequestManager _requestManager;
public IdentifiedCommandHandler(IMediator mediator, IRequestManager requestManager)
{
_mediator = mediator;
_requestManager = requestManager;
}
/// <summary>
/// Creates the result value to return if a previous request was found
/// </summary>
/// <returns></returns>
protected virtual R CreateResultForDuplicateRequest()
{
return default(R);
}
/// <summary>
/// This method handles the command. It just ensures that no other request exists with the same ID, and if this is the case
/// just enqueues the original inner command.
/// </summary>
/// <param name="message">IdentifiedCommand which contains both original command & request ID</param>
/// <returns>Return value of inner command or default value if request same ID was found</returns>
public async Task<R> Handle(IdentifiedCommand<T, R> message, CancellationToken cancellationToken)
{
var alreadyExists = await _requestManager.ExistAsync(message.Id);
if (alreadyExists)
{
return CreateResultForDuplicateRequest();
}
else
{
await _requestManager.CreateRequestForCommandAsync<T>(message.Id);
var result = await _mediator.Send(message.Command);
return result;
}
}
}
我将不胜感激。我不得不对其进行一些更改以使其与当前的 MediatR 兼容,因此我使用 IRequestHandler 而不是 IAsyncRequestHandler,因为它不再存在。