Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding one class to several interfaces as singleton

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?

like image 839
iburlakov Avatar asked Nov 16 '10 14:11

iburlakov


2 Answers

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.

like image 68
Steven Avatar answered Sep 20 '22 12:09

Steven


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>();
like image 37
Remo Gloor Avatar answered Sep 24 '22 12:09

Remo Gloor