Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind multiple implementations to the same interface with ninject

Tags:

Why is it not possible for me to do the following in Ninect?

Kernel.Bind<IPresenter>.To<DefaultPresenter>(); Kernel.Bind<IPresenter>.To<DashboardPresenter>(); Kernel.Bind<IPresenter>.To<HeartRatePresenter>(); Kernel.Bind<IPresenter>.To<GPSPresenter>(); 

Each of the 4 implementations have a different constructor that expect a different type. When i attempt this, Ninject throws an exception telling me that i cannot bind to the same interface more than once.

In a class called Presentable which all presenter classes inherit from, I am attempting to do Kernel.Get<IPresenter>(new ConstructorArgument("view", this)) so assign IPresentable Presenter within the page/view where the page/view implements an interface that the presenter expects as a parameter.

What is a way around this so that ninject recognises different constructor parameter types?

like image 937
bizzehdee Avatar asked Jan 22 '14 15:01

bizzehdee


1 Answers

The binding to multiple interfaces is fine. Ninject allows this. see here: https://github.com/ninject/Ninject/wiki/Multi-injection

The problem is that Ninject can not just magically give you the "one" that you want depending on constructor arguments. What Ninject is designed to do with the code you wrote is to give you ALL of the bindings at once, when you ask for a List.

So like others said, if you only want a single instance, it sounds like what you want is contextual bindings. However, the way you asked your question and the other answers are a bit confusing, because it makes it sound like multi-injection is not possible, but it is possible, if it is really what you want. (which in this case it isn't)

like image 175
Robert Noack Avatar answered Oct 01 '22 07:10

Robert Noack