c# – Autofac解析相同类型的多个实例

我的应用程序中有一个稍微修改过的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> { }

解决方法:

经过大量的故障排除后,我发现我实际上是在两次注册我的处理程序.我喜欢使用Autofac Modules将容器的配置分解为可管理的块.

在我的MVC5 Startup类中,我注册了我的模块,如下所示:

builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

深入埋藏在“InfrastructureModule”类中的是:

builder.RegisterModule<MediatorModule>();

这当然是重新注册我的调解员处理程序…… DUH ..

上一篇:c# – NInject相当于Autofac的AsClosedTypesOf


下一篇:c# – Autofac,IDisposable和手动呼叫.在某些情况下解决