我的应用程序中有一个稍微修改过的Mediatr处理命令处理版本。我已经实现了一个 MediatorPipeline,它允许我拥有前处理器和后处理器。
public class AsyncMediatorPipeline<TRequest, TResponse>
: IAsyncRequestHandler<TRequest, TResponse>
where TRequest : IAsyncRequest<TResponse>
{
private readonly IAsyncRequestHandler<TRequest, TResponse> inner;
private readonly IAsyncPreRequestHandler<TRequest>[] preRequestHandlers;
private readonly IAsyncPostRequestHandler<TRequest,TResponse>[] postRequestHandlers;
public AsyncMediatorPipeline(IAsyncRequestHandler<TRequest, TResponse> inner,
IAsyncPreRequestHandler<TRequest>[] preRequestHandlers,
IAsyncPostRequestHandler<TRequest, TResponse>[] postRequestHandlers)
{
this.inner = inner;
this.preRequestHandlers = preRequestHandlers;
this.postRequestHandlers = postRequestHandlers;
}
public async Task<TResponse> Handle(TRequest message)
{
foreach (var preRequestHandler in preRequestHandlers)
{
await preRequestHandler.Handle(message);
}
var result = await inner.Handle(message);
foreach (var postRequestHandler in postRequestHandlers)
{
await postRequestHandler.Handle(message, result);
}
return result;
}
}
我正在使用 autofac 注册我的预处理器,如下所示:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.As(type => type.GetInterfaces()
.Where(type => type.IsClosedTypeOf(typeof(IAsyncPreRequestHandler<>))))
.InstancePerLifetimeScope();
在运行时,我得到了重复的预处理器。我必须过滤删除重复项的集合。我不确定为什么会这样。如果我注释掉注册,我没有得到任何预处理器,这表明我没有在其他地方复制注册。
更新:这里有一些关于似乎被注册两次的类型的更多细节。各种类定义:
混凝土搬运工
public class ClientEditorFormIdentifierValidationHandler
: IAsyncPreRequestHandler<AddOrEditClientCommand>{}
命令类
public class AddOrEditClientCommand
: IAsyncRequest<ICommandResult>{}
命令界面
public interface IAsyncRequest<out TResponse> { }