我有以下(简化的)情况:我有两个接口(interface)
interface IAmAnInterface
{
void DoSomething();
}
和
interface IAmAnInterfaceToo
{
void DoSomethingElse();
}
和一个实现两者的类:
class IAmAnImplementation: IAmAnInterface, IAmAnInterfaceToo
{
public IAmAnImplementation()
{
}
public void DoSomething()
{
}
public void DoSomethingElse()
{
}
}
现在我使用 Ninject 将同一个类绑定(bind)到两个接口(interface)。因为我想要 IAmAnImplementation
的相同实例蜜蜂用于IAmAnInterface
以及IAmAnInterfaceToo
很明显,我需要某种单例。我玩弄了 ninject.extensions.namedscope以及InScope()
但没有成功。我最后一次尝试是:
Bind<IAmAnImplementation>().ToSelf().InSingletonScope();
Bind<IAmAnInterface>().To<IAmAnImplementation>().InSingletonScope();
Bind<IAmAnInterfaceToo>().To<IAmAnImplementation>().InSingletonScope();
但不幸的是,当我通过 kernel.Get<IDependOnBothInterfaces>();
请求我的测试类实例时它实际上使用了 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非常简单
Bind<I1, I2, I3>().To<Impl>().InSingletonScope();
关于c# - 是否可以将不同的接口(interface)绑定(bind)到实现所有接口(interface)的类的同一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10206049/