0

我正在尝试使用 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>>它时,它会失败,除了:

容器或服务定位器未正确配置或处理程序未在您的容器中注册。---> 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);
}

任何建议都非常感谢!

4

1 回答 1

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");
于 2016-12-13T05:31:36.137 回答