简体   繁体   English

Ninject绑定,接口到接口

[英]Ninject Binding, Interface to Interface

I want to do something along the lines of this: 我想做一些类似的事情:

kernel.Bind<IBootTaskA>().To<BootTaskA>().InSingletonScope();
kernel.Bind<IBootTaskB>().To<BootTaskB>().InSingletonScope();

kernel.Bind<IBootTask>().To<IBootTaskA>();
kernel.Bind<IBootTask>().To<IBootTaskB>();

So i can do this: 所以我可以这样做:

public class Boot
{
     public Boot(IBootTask[] bootTasks)
     {
          foreach(var task in bootTasks){task.Execute();}
     }
}

but i cant seem to bind an interface to an interface, anyone know a way around this? 但我似乎无法将接口绑定到接口,有人知道解决方法吗?

Heres how you do it. 这是您的操作方式。

public class Service : IServiceA, IServiceB {}

this.Bind<Service>().ToSelf().InSingletonScope();
kernel.BindInterfaceToBinding<IServiceA, Service>();
kernel.BindInterfaceToBinding<IServiceB, Service>();

The ninject extention handles what you need. ninject扩展可满足您的需求。

https://github.com/ninject/ninject.extensions.contextpreservation/wiki/Bind-Interface-to-Binding https://github.com/ninject/ninject.extensions.contextpreservation/wiki/Bind-Interface-to-Binding

EDIT: 编辑:

In ninject 3 this is slightly easier, you no longer need contextpreservation, Simply: 在ninject 3中,这稍微容易些,您不再需要上下文保存,只需:

Bind<IServiceA,IServiceB>().To<Service>().InSingletonScope();

UPDATE: The V3 Bind overloads address a lot of this. 更新: V3绑定重载解决了很多此类问题。


Ninject doesnt have any constructs of that nature (and I'm not aware of other containers having such a system either). Ninject没有这种性质的构造(我也不知道其他具有这种系统的容器)。

I suspect some form of Conditional Bindings may be most appropriate for your real problem (I assume you dont really have common marker interfaces exactly as you show). 我怀疑某种形式的条件绑定可能最适合您的实际问题(我假设您确实没有显示的通用标记界面)。

Or are you just trying to find a construct to keep your bindings DRY? 还是您只是想寻找一种使绑定保持干燥的结构? I personally would express the above as two bindings with a custom .WithStandardTaskProperties extension method rather than 4 lines. 我个人将上述内容表示为带有自定义.WithStandardTaskProperties扩展方法的两个绑定,而不是4行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM