40

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?

mipe34
  • 5,596
  • 3
  • 26
  • 38
Silas
  • 1,140
  • 11
  • 12
  • related: See [this V2-era question](http://stackoverflow.com/questions/3147996/binding-singleton-to-multiple-services-in-ninject) for overly detailed discussions of old invalid approaches – Ruben Bartelink Nov 30 '12 at 11:23

1 Answers1

107

It is very easy using V3.0.0

Bind<I1, I2, I3>().To<Impl>().InSingletonScope();
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98