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 ImplCla开发者_如何转开发ss : 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>();
This is how you can do it in one line of code:
Bind<IInterface1 ,IInterface2 ,ImplClass>().To<ImplClass>().InSingletonScope();
https://github.com/ninject/Ninject.Extensions.ContextPreservation/wiki/BindInterfaceToBinding
It requires Ninject version 3.
I would suspect this would create two instances.
Try whether the following construct works for you:
public class ImplClass : IInterface1, IInterface2
{
public static readonly ImplClass Instance = new ImplClass();
}
With the following binding:
Bind<IInterface1>().ToMethod(c => ImplClass.Instance);
Bind<IInterface2>().ToMethod(c => ImplClass.Instance);
精彩评论