使用Autofac解析IEnumerable

时间:2016-11-13 11:02:45

标签: c# autofac mediatr

我正在尝试使用Mediatr和Autofac构建中介管道,但我正在努力解决Autofac中的验证器集合。

public class MediatorPipeline<TRequest, TResponse>
    : IAsyncRequestHandler<TRequest, TResponse> where TRequest : IAsyncRequest<TResponse>
{
    private readonly IAsyncRequestHandler<TRequest, TResponse> _inner;
    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public MediatorPipeline(IAsyncRequestHandler<TRequest, TResponse> inner,
        IEnumerable<IValidator<TRequest>> validators)
    {
        _inner = inner;
        _validators = validators;
    }
    ...
}

当我在构造函数中放置IValidator<TRequest>时它解析得很好,但是当我放IEnumerable<IValidator<TRequest>>它失败时,除了:

  

未正确配置容器或服务定位器或未在容器中注册的处理程序。 ---&GT; Autofac.Core.DependencyResolutionException:在激活特定注册期间发生错误。

这是我的注册码:

builder.RegisterAssemblyTypes(assembly)
    .Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

我在这个替代注册中获得了相同的结果:

var openGenericType = typeof(IValidator<>);

var query = from type in assembly.GetTypes().Where(c => !(c.GetTypeInfo().IsAbstract || c.GetTypeInfo().IsGenericTypeDefinition))
            let interfaces = type.GetInterfaces()
            let genericInterfaces = interfaces.Where(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == openGenericType)
            let matchingInterface = genericInterfaces.FirstOrDefault()
            where matchingInterface != null
            select new { matchingInterface, type };

foreach (var pair in query)
{
    builder.RegisterType(pair.type).As(pair.matchingInterface);
}

任何建议都非常感谢!

1 个答案:

答案 0 :(得分:0)

首先,很高兴看到包含内部异常的整个异常 - 堆栈跟踪。

Autofac公开了一种方便的扩展方法AsClosedTypesOf,您可以这样使用:

builder
    .RegisterAssemblyTypes(ThisAssembly)
    .AsClosedTypesOf(typeof(IValidator<>))
    .InstancePerLifetimeScope();

这将为您完成工作,因此您不必深入思考注册您的验证人。

然后,您需要在其上注册处理程序和装饰器:

builder
    .RegisterAssemblyTypes(ThisAssembly)
    .AsClosedTypesOf(typeof(IAsyncRequestHandler<,>), "base-handler")
    .InstancePerDependency();

builder.RegisterGenericDecorator(
    typeof(MediatorPipeline<,>),
    typeof(IAsyncRequestHandler<,>),
    "base-handler");