将一个类绑定到多个接口作为单例

ibu*_*kov 18 c# singleton binding dependency-injection ninject

我有例如2个interfases IInterface1IInterface2,

public interface IInterface1 {...}
public interface IInterface2 {...} 
Run Code Online (Sandbox Code Playgroud)

以及这些接口的一个实现ImplClass.

public class ImplClass : IInterface1, IInterface2 {...}
Run Code Online (Sandbox Code Playgroud)

我必须确保应用程序只有一个ImplClass实例,它将用作IInterface1和IInterface2.我正在使用ninject进行依赖注入.所以我的问题是:下面的代码是否符合我的要求?

...
Bind<IInterface1>().To<ImplClass>().Using<SingletonBehavior>();
Bind<IInterface2>().To<ImplClass>().Using<SingletonBehavior>();
...
Run Code Online (Sandbox Code Playgroud)

或者此代码将为eash接口创建2个ImplClass实例?

Ste*_*ven 20

使用Ninject,你可以这样做:

var impl = new Impl();
container.Bind<IInt1>().ToMethod(c => impl);
container.Bind<IInt2>().ToMethod(c => impl);
Run Code Online (Sandbox Code Playgroud)

Impl类具有依赖项时,您无法注入Ninject,您可以这样做:

container.Bind<Impl>().ToSelf().InSingletonScope();
container.Bind<IInt1>().ToMethod(c => c.Kernel.Get<Impl>());
container.Bind<IInt2>().ToMethod(c => c.Kernel.Get<Impl>()); 
Run Code Online (Sandbox Code Playgroud)

干净整洁.

  • (更好的答案,直到这个重复的问题消失是http://stackoverflow.com/questions/10206049/ninject-is-it-possible-to-bind-different-interfaces-to-the-same-instance-of-ac) (4认同)

Rem*_*oor 5

看来你还在使用Ninject 1.5.我不再考虑确切的语法了,但它应该类似于以下2.1语法:

kernel.Bind<I1>().ToMethod(ctx => ctx.Kernel.Get<Impl>());
kernel.Bind<I2>().ToMethod(ctx => ctx.Kernel.Get<Impl>()); 
kernel.Bind<Impl>().ToSelf().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)

或者甚至更好地使用Ninject.Extensions.ContextPreservation来保持上下文.

kernel.Bind<Impl>().ToSelf().InSingletonScope();
kernel.BindInterfaceToBinding<I1, Impl>();
kernel.BindInterfaceToBinding<I2, Impl>();
Run Code Online (Sandbox Code Playgroud)