Ninject Binding, Interface to Interface

做~自己de王妃 提交于 2019-12-05 04:58:29

问题


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?


回答1:


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.

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:

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



回答2:


UPDATE: The V3 Bind overloads address a lot of this.


Ninject doesnt have any constructs of that nature (and I'm not aware of other containers having such a system either).

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.



来源:https://stackoverflow.com/questions/8303661/ninject-binding-interface-to-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!