我想将一些动物注册为单例,所以我用以下代码编写了一个结构图注册表:
this.For<ILion>.Use<Lion>().Singleton();
this.For<IElephant>.Use<Elephant>().Singleton();ILion和IElephant来源于IAnimal,我也想要一次得到所有动物的可能性。我试过:
this.For<IAnimal>.Add<Lion>().Singleton();
this.For<IAnimal>.Add<Elephant>().Singleton();但这为每个接口提供了两个不同的Lion实例:
public AnyConstructor(ILion lion, IEnumerable<IAnimal> animals)
{
// lion == animals[0] should be true here, but is false
}如何才能告诉结构图只实例化一狮子
发布于 2015-07-14 12:31:10
如果您的意思是要获得两个不同的Lion实例,您可以在注册表中使用这样的Forward<TFrom, TTo>()方法:
this.For<ILion>().Use<Lion>().Singleton();
this.For<IElephant>().Use<Elephant>().Singleton();
this.Forward<ILion, IAnimal>();
this.Forward<IElephant, IAnimal>(); 然后,要获取所有IAnimal实例,请使用如下所示的GetAllInstances<T>()方法:
var lion = ObjectFactory.GetInstance<ILion>();
var elephant = ObjectFactory.GetInstance<IElephant>();
var animal = ObjectFactory.GetAllInstances<IAnimal>();https://stackoverflow.com/questions/31406484
复制相似问题