问题描述
我有以下的(简化)情况:我有两个接口
I have the following (simplified) situation: I have two interfaces
interface IAmAnInterface
{
void DoSomething();
}
和
interface IAmAnInterfaceToo
{
void DoSomethingElse();
}
和实施这两个类:
class IAmAnImplementation: IAmAnInterface, IAmAnInterfaceToo
{
public IAmAnImplementation()
{
}
public void DoSomething()
{
}
public void DoSomethingElse()
{
}
}
现在我同班绑定使用Ninject两个接口。因为我想的相同的实例的 IAmAnImplementation
的beeing用于 IAmAnInterface
以及 IAmAnInterfaceToo
很显然,我需要某种形式的单身人士。我以及发挥各地InScope()
,但没有成功。我最后的尝试是:
Now I bind the same class to both interfaces using Ninject. Since I want the same instance of IAmAnImplementation
beeing used for IAmAnInterface
as well as IAmAnInterfaceToo
it's clear that I need some kind of singleton. I played around with ninject.extensions.namedscope as well as InScope()
but had no success. My last try was:
Bind<IAmAnImplementation>().ToSelf().InSingletonScope();
Bind<IAmAnInterface>().To<IAmAnImplementation>().InSingletonScope();
Bind<IAmAnInterfaceToo>().To<IAmAnImplementation>().InSingletonScope();
但不幸的是,当我通过请我的测试类的实例 kernel.Get&LT; IDependOnBothInterfaces&GT;();
它实际上使用的不同实例IAmAnImplementation
。
class IDependOnBothInterfaces
{
private IAmAnInterface Dependency1 { get; set; }
private IAmAnInterfaceToo Dependency2 { get; set; }
public IDependOnBothInterfaces(IAmAnInterface i1, IAmAnInterfaceToo i2)
{
Dependency1 = i1;
Dependency2 = i2;
}
public bool IUseTheSameInstances
{
get { return Dependency1 == Dependency2; } // returns false
}
}
有没有办法告诉Ninject使用 IAmAnImplementation
的同一个实例为 IAmAnInterface
以及 IAmAnInterfaceToo
?
推荐答案
这是很容易使用V3.0.0
It is very easy using V3.0.0
Bind<I1, I2, I3>().To<Impl>().InSingletonScope();
这篇关于是否有可能不同的接口绑定到实现所有这些类的同一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!