StructureMap - 为多个接口注册单例
StructureMap - Register a singleton for multiple interfaces
我想将一些动物注册为单例,所以我写了一个结构图注册表,代码如下:
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
}
如何告诉结构图只实例化一个 Lion?
如果您的意思是您获得了两个不同的 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>();
我想将一些动物注册为单例,所以我写了一个结构图注册表,代码如下:
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
}
如何告诉结构图只实例化一个 Lion?
如果您的意思是您获得了两个不同的 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>();