使用ninject将多个实现绑定到同一接口 [英] Bind multiple implementations to the same interface with ninject

查看:135
本文介绍了使用ninject将多个实现绑定到同一接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我无法在Ninect中执行以下操作?

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

4个实现中的每个实现都有一个不同的构造函数,这些构造函数期望使用不同的类型.当我尝试这样做时,Ninject抛出一个异常,告诉我我不能多次绑定到同一接口.

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.

在所有演示者类都继承的名为Presentable的类中,我尝试执行Kernel.Get<IPresenter>(new ConstructorArgument("view", this)),因此在页面/视图内分配IPresentable Presenter,其中页面/视图实现了演示者期望作为参数的接口

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.

有什么方法可以使ninject识别不同的构造函数参数类型?

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

推荐答案

与多个接口的绑定很好. Ninject允许这样做.参见此处: https://github.com/ninject/Ninject/wiki/Multi-injection

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

问题在于Ninject不能仅仅根据构造函数的参数神奇地给您想要的一个". Ninject旨在与您编写的代码一起使用,是在您请求列表时立即为您提供所有绑定.

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)

这篇关于使用ninject将多个实现绑定到同一接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆