我有以下(简化)情况:我有两个接口
interface IAmAnInterface
{
void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
和
interface IAmAnInterfaceToo
{
void DoSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)
和一个实现两者的类:
class IAmAnImplementation: IAmAnInterface, IAmAnInterfaceToo
{
public IAmAnImplementation()
{
}
public void DoSomething()
{
}
public void DoSomethingElse()
{
}
}
Run Code Online (Sandbox Code Playgroud)
现在我使用Ninject将同一个类绑定到两个接口.因为我想要使用相同的IAmAnImplementationbeeing 实例,IAmAnInterface而且IAmAnInterfaceToo很明显我需要某种单例.我和ninject.extensions.namedscope一起玩,InScope()但没有成功.我的最后一次尝试是:
Bind<IAmAnImplementation>().ToSelf().InSingletonScope();
Bind<IAmAnInterface>().To<IAmAnImplementation>().InSingletonScope();
Bind<IAmAnInterfaceToo>().To<IAmAnImplementation>().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)
但不幸的是,当我通过kernel.Get<IDependOnBothInterfaces>();它请求我的测试类的实例时实际上使用了不同的实例IAmAnImplementation.
class IDependOnBothInterfaces
{
private IAmAnInterface Dependency1 { get; set; }
private IAmAnInterfaceToo Dependency2 { get; set; }
public IDependOnBothInterfaces(IAmAnInterface i1, …Run Code Online (Sandbox Code Playgroud) c# dependency-injection ninject inversion-of-control ninject-3