Ninject Binding, Interface to Interface

余生颓废 提交于 2019-12-03 21:11:12

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();

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.

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