Autofac可以解析同一类型的多个实例

时间:2015-03-09 21:15:25

标签: c# autofac mediatr

我在我的应用程序中稍微修改了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();

在运行时,我正在获得重复的preprcessors。我必须过滤删除副本的集合。我不确定为什么会这样。如果我注释掉注册,我没有得到任何预处理器,这表明我没有在其他地方重复注册。

更新:以下是有关此类似乎已注册两次的详细信息。各种类定义:

具体处理程序

public class ClientEditorFormIdentifierValidationHandler 
: IAsyncPreRequestHandler<AddOrEditClientCommand>{}

命令类

public class AddOrEditClientCommand 
: IAsyncRequest<ICommandResult>{}

命令界面

public interface IAsyncRequest<out TResponse> { }

1 个答案:

答案 0 :(得分:2)

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

在我的MVC5 Startup类中,我注册了我的模块:

builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

埋藏在&#34; InfrastructureModule&#34;上课就是这句话:

builder.RegisterModule<MediatorModule>();

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