我正在尝试使用 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);
}
任何建议都非常感谢!