是否可以将不同的接口绑定到实现所有接口的类的同一个实例? [英] Is it possible to bind different interfaces to the same instance of a class implementing all of them?
问题描述
我有以下(简化的)情况:我有两个接口
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
的 相同实例 用于 IAmAnInterface
以及 IAmAnInterfaceToo
很明显我需要一些一种单身.我玩过 ninject.extensions.namedscope 以及 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<IDependOnBothInterfaces>();
请求我的测试类的实例时,它实际上使用了 IAmAnImplementation
的不同实例.
But unfortunately when I request an instance of my test class via kernel.Get<IDependOnBothInterfaces>();
it in fact uses different instances of 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 对 IAmAnInterface
和 IAmAnInterfaceToo
使用相同的 IAmAnImplementation
实例?
Is there a way tell Ninject to use the same instance of IAmAnImplementation
for IAmAnInterface
as well as IAmAnInterfaceToo
?
推荐答案
使用V3.0.0非常简单
It is very easy using V3.0.0
Bind<I1, I2, I3>().To<Impl>().InSingletonScope();
这篇关于是否可以将不同的接口绑定到实现所有接口的类的同一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!