是否可以将不同的接口绑定到实现所有接口的同一个实例?

Sil*_*las 38 c# dependency-injection ninject inversion-of-control ninject-3

我有以下(简化)情况:我有两个接口

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, IAmAnInterfaceToo i2)
    {
        Dependency1 = i1;
        Dependency2 = i2;
    }

    public bool IUseTheSameInstances
    {
        get { return Dependency1 == Dependency2; } // returns false
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让Ninject使用相同的IAmAnImplementationfor 实例IAmAnInterface以及IAmAnInterfaceToo

Rem*_*oor 101

使用V3.0.0非常容易

Bind<I1, I2, I3>().To<Impl>().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)

  • 如果你有4个以上的接口:`Bind(I1,I2,I3,I4,I5).To <Impl>().InSingletonScope();` (7认同)