I am trying to build a mediator pipeline with Mediatr and Autofac but am struggling to resolve a collection of validators from 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;
}
...
}
When I put IValidator<TRequest>
in the constructor it resolves fine, but when I put IEnumerable<IValidator<TRequest>>
it fails, with the exception:
Container or service locator not configured properly or handlers not registered with your container. ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration.
Here is my registration code:
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
I had the same result with this alternative registration:
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);
}
Any suggestions much appreciated!