I have for instance 2 interfases IInterface1
and IInterface2
,
public interface IInterface1 {...}
public interface IInterface2 {...}
and one implementation of these interfaces ImplClass
.
public class ImplClass : IInterface1, IInterface2 {...}
I have to be sure that application has only one instance of ImplClass, which will be used as IInterface1 and IInterface2. I'm using ninject for dependency injection. So my qustion is: Does code below will meet my requirements?
...
Bind<IInterface1>().To<ImplClass>().Using<SingletonBehavior>();
Bind<IInterface2>().To<ImplClass>().Using<SingletonBehavior>();
...
Or this code will create 2 instances of ImplClass, for eash interface?
With Ninject you can do this:
var impl = new Impl();
container.Bind<IInt1>().ToMethod(c => impl);
container.Bind<IInt2>().ToMethod(c => impl);
When the Impl
class has dependencies you can't Ninject to inject, you can do this:
container.Bind<Impl>().ToSelf().InSingletonScope();
container.Bind<IInt1>().ToMethod(c => c.Kernel.Get<Impl>());
container.Bind<IInt2>().ToMethod(c => c.Kernel.Get<Impl>());
Nice and clean.
It seems that you're still using Ninject 1.5. I havn't the exact syntax in mind anymore but it should be similat to the following 2.1 syntax:
kernel.Bind<I1>().ToMethod(ctx => ctx.Kernel.Get<Impl>());
kernel.Bind<I2>().ToMethod(ctx => ctx.Kernel.Get<Impl>());
kernel.Bind<Impl>().ToSelf().InSingletonScope();
Or even better use Ninject.Extensions.ContextPreservation to keep the context.
kernel.Bind<Impl>().ToSelf().InSingletonScope();
kernel.BindInterfaceToBinding<I1, Impl>();
kernel.BindInterfaceToBinding<I2, Impl>();
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