Is it possible to bind different interfaces to the same instance of a class implementing all of them?
Asked Answered
S

1

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?

Subhead answered 18/4, 2012 at 8:56 Comment(1)
related: See this V2-era question for overly detailed discussions of old invalid approachesClachan
A
107

It is very easy using V3.0.0

Bind<I1, I2, I3>().To<Impl>().InSingletonScope();
Aniseed answered 18/4, 2012 at 9:32 Comment(5)
+1 thanks. In fact I'm using 3.0 so I'll go for this solution.Subhead
If you have more than 4 interfaces: Bind(I1, I2, I3, I4, I5).To<Impl>().InSingletonScope();Deformity
Can you please explain how this needs to be integrated with above scenario?Bartle
This is nice when you know all your interfaces at compile time, but not so much when you need to scan for them at runtime.Whitefish
Ahh man, i had two bindings instead of multiple interfaces, which resulted in having one singleton per interface.Gun

© 2022 - 2024 — McMap. All rights reserved.