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
?
Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.
C# allows that a single class can implement multiple interfaces at a time, and also define methods and variables in that interface.
Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.
C# allows the implementation of multiple interfaces with the same method name.
It is very easy using V3.0.0
Bind<I1, I2, I3>().To<Impl>().InSingletonScope();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With