CollectionResolver
More generic alternative to ArrayResolver and ListResolver.
It supports arrays as well as any generic interface type assignable from arrays.
using Castle.Core;
using Castle.Core.Internal;
using Castle.MicroKernel.Context;
using System;
namespace Castle.MicroKernel.Resolvers.SpecializedResolvers
{
public class CollectionResolver : ISubDependencyResolver
{
protected readonly bool allowEmptyCollections;
protected readonly IKernel kernel;
public CollectionResolver(IKernel kernel, bool allowEmptyCollections = false)
{
this.kernel = kernel;
this.allowEmptyCollections = allowEmptyCollections;
}
public virtual bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
if (dependency.TargetItemType == (Type)null)
return false;
Type itemType = GetItemType(dependency.TargetItemType);
if (itemType != (Type)null && !HasParameter(dependency))
return CanSatisfy(itemType);
return false;
}
public virtual object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
return kernel.ResolveAll(GetItemType(dependency.TargetItemType), context.AdditionalArguments);
}
protected virtual bool CanSatisfy(Type itemType)
{
if (!allowEmptyCollections)
return kernel.HasComponent(itemType);
return true;
}
protected virtual Type GetItemType(Type targetItemType)
{
return targetItemType.GetCompatibleArrayItemType();
}
protected virtual bool HasParameter(DependencyModel dependency)
{
return dependency.Parameter != null;
}
}
}