If you don't want to change the signature of MyService and keep using IEnumerable<IRule>
, you can also create a custom ISubDependencyResolver. That's what we did:
public class EnumerableResolver : ISubDependencyResolver
{
private readonly IKernel kernel;
public EnumerableResolver(IKernel kernel)
{
this.kernel = kernel;
}
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
Type targetType = dependency.TargetType;
if (targetType == null)
{
throw new ArgumentException("TargetType property cannot be null", "dependency");
}
if (targetType.IsGenericType && (targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
Type service = targetType.GetGenericArguments()[0];
return this.kernel.HasComponent(service);
}
return false;
}
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
Type service = dependency.TargetType.GetGenericArguments()[0];
Array array = this.kernel.ResolveAll(service, (IDictionary)null);
return Activator.CreateInstance(typeof(List<>).MakeGenericType(new Type[] { service }), new object[] { array });
}
}
It needs to be registered with the container like this:
container.Kernel.Resolver.AddSubResolver(new EnumerableResolver(this.Kernel));