Ninject Binding, Interface to Interface

2019-04-01 18:09发布

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?

2条回答
老娘就宠你
2楼-- · 2019-04-01 18:30

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();
查看更多
看我几分像从前
3楼-- · 2019-04-01 18:31

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.

查看更多
登录 后发表回答