Is it possible to bind different interfaces to the

2020-01-29 06:24发布

问题:

I have the following (simplified) situation: I have two interfaces

interface IAmAnInterface
{
    void DoSomething();
}

and

interface IAmAnInterfaceToo
{
    void DoSomethingElse();
}

and a class implementing both:

class IAmAnImplementation: IAmAnInterface, IAmAnInterfaceToo
{
    public IAmAnImplementation()
    {
    }

    public void DoSomething()
    {
    }

    public void DoSomethingElse()
    {
    }
}

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();

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
    }
}

Is there a way tell Ninject to use the same instance of IAmAnImplementation for IAmAnInterface as well as IAmAnInterfaceToo?

回答1:

It is very easy using V3.0.0

Bind<I1, I2, I3>().To<Impl>().InSingletonScope();