2

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?

cuongle
  • 74,024
  • 28
  • 151
  • 206
undefined
  • 33,537
  • 22
  • 129
  • 198

2 Answers2

6

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();
undefined
  • 33,537
  • 22
  • 129
  • 198
1

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.

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
  • The real problem sparking this is that I actually need to inject these in other places as well as the boot loader. That means i actually need 2 different bindings for the instance, one to get a generic list to load and then also to get an individual instance to act on. The problem is that if I bind them seperatly they will go to different singleton instances. – undefined Nov 28 '11 at 23:45
  • Have a look around - there are two answers about in this tag this year which have answers demonstrating the `Bind...` `.ToBinding` (IIRC) construct - one with an answer from @Remo Gloor (And if you're using Ninject in any way, you should go read all his top answers as your first thing anyway) – Ruben Bartelink Nov 29 '11 at 08:40
  • Ta for the upvote (your answer had mine from ages back) - my answer from back in the day obv wasnt much use. I've added related: links up top and there are one or two dups of the bind multiple interfaces question that need Voting to Close. This question is different enough to warrant definitely staying [and a great example of the Self-Learner badge in action!]. – Ruben Bartelink Sep 12 '12 at 10:17