如果你不想改變的MyService的簽名,並保持使用IEnumerable<IRule>
,你也可以創建一個自定義的ISubDependencyResolver。這就是我們所做的:
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 });
}
}
它需要像這樣的集裝箱進行註冊:
container.Kernel.Resolver.AddSubResolver(new EnumerableResolver(this.Kernel));
從昨天看到這個職位由邁克:http://mikehadlow.blogspot.com/2008/09 /resolving-arrays-with-windsor.html – 2010-01-15 08:27:19