C# 温莎城堡:如何注入所有工厂的集合?
使用Castle Windsor,我希望获得实现特定接口的所有工厂的集合 假设您具有以下类型层次结构:C# 温莎城堡:如何注入所有工厂的集合?,c#,dependency-injection,castle-windsor,C#,Dependency Injection,Castle Windsor,使用Castle Windsor,我希望获得实现特定接口的所有工厂的集合 假设您具有以下类型层次结构: public interface IAnimal { } public class Cat : IAnimal { } public class Dog : IAnimal { } 使用TypedFactoryFacility我能够注入一个Func,它作为工厂来创建动物实例(具有短暂的生命周期)。我还可以使用CollectionResolver解析具有单一生命周期的动物集合。但在下面的示例中
public interface IAnimal { }
public class Cat : IAnimal { }
public class Dog : IAnimal { }
使用TypedFactoryFacility
我能够注入一个Func
,它作为工厂来创建动物实例(具有短暂的生命周期)。我还可以使用CollectionResolver
解析具有单一生命周期的动物集合。但在下面的示例中,似乎无法将TypedFactoryFacility
和CollectionResolver
的效果组合起来解析工厂集合
public class Zoo
{
public Zoo(IEnumerable<Func<IAnimal>> animalFactories)
{
foreach (Func<IAnimal> factory in animalFactories)
{
IAnimal animal = factory();
Console.WriteLine(animal.GetType());
}
}
}
class Test
{
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
container.Register(Component.For<IAnimal>().ImplementedBy<Cat>().LifestyleTransient());
container.Register(Component.For<IAnimal>().ImplementedBy<Dog>().LifestyleTransient());
container.Register(Component.For<Zoo>());
container.ResolveAll<IAnimal>();
container.Resolve<Zoo>();
}
}
您必须执行以下步骤:
另一种方法是将工厂类型作为委托进行描述、、谢谢您的回答,但出于某些原因,我需要将工厂作为委托人:(
Component Zoo has a dependency on System.Collections.Generic.IEnumerable`1[System.Func`1[IAnimal]], which could not be resolved.