StructureMap——为多个接口注册一个单例

本文关键字:一个 单例 接口 StructureMap 注册 | 更新日期: 2023-09-27 18:02:40

我想将一些动物注册为单例,所以我用下面的代码编写了一个结构映射注册表:

this.For<ILion>.Use<Lion>().Singleton();
this.For<IElephant>.Use<Elephant>().Singleton();

ILionIElephant源自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
}

我如何告诉结构映射只实例化一个Lion?

StructureMap——为多个接口注册一个单例

如果您的意思是您正在获得两个不同的Lion实例,您可以在注册表中使用Forward<TFrom, TTo>()方法:

this.For<ILion>().Use<Lion>().Singleton();
this.For<IElephant>().Use<Elephant>().Singleton();
this.Forward<ILion, IAnimal>();
this.Forward<IElephant, IAnimal>(); 

然后,使用GetAllInstances<T>()方法获取所有IAnimal实例,如下所示:

var lion = ObjectFactory.GetInstance<ILion>();
var elephant = ObjectFactory.GetInstance<IElephant>();
var animal = ObjectFactory.GetAllInstances<IAnimal>();