undefined
undefined

Reputation: 34309

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?

Upvotes: 2

Views: 1971

Answers (2)

undefined
undefined

Reputation: 34309

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

Upvotes: 6

Ruben Bartelink
Ruben Bartelink

Reputation: 61903

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.

Upvotes: 1

Related Questions