【问题标题】:Bind multiple implementations to the same interface with ninject使用 ninject 将多个实现绑定到同一个接口
【发布时间】:2014-01-22 15:52:26
【问题描述】:

为什么我不能在 Ninect 中执行以下操作?

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

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

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

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

【问题讨论】:

    标签: c# ninject


    【解决方案1】:

    绑定到多个接口很好。 Ninject 允许这样做。看这里:https://github.com/ninject/Ninject/wiki/Multi-injection

    问题在于,Ninject 不能仅仅根据构造函数参数神奇地给你想要的“一个”。 Ninject 旨在对您编写的代码执行的操作是在您请求列表时立即为您提供所有绑定。

    就像其他人所说,如果您只想要一个实例,听起来您想要的是上下文绑定。但是,您提出问题和其他答案的方式有点令人困惑,因为这听起来像是不可能进行多次注射,但如果它真的是您想要的,那么它是可能的。 (在这种情况下不是)

    【讨论】:

      【解决方案2】:

      您需要告诉 ninject 它应该如何知道选择哪个绑定。

      看看条件绑定: https://github.com/ninject/ninject/wiki/Contextual-Binding

      我建议使用.When(...) 语法,但也许您更喜欢使用.Named(...)(即为每个绑定分配一个名称/标识符,并将该名称传递给.Get&lt;IPresenter&gt;("SomeName") 调用中的ninject)。

      【讨论】:

      • 那个帮助页面是shiznit!很不错
      • 如果请求类有属性名则绑定:Bind&lt;IMessageService&gt;().To&lt;MailingService&gt;().When(request =&gt; (((System.Reflection.PropertyInfo[])((System.Reflection.TypeInfo)((request.Target.Member).ReflectedType)).DeclaredProperties)[0]).Name.Contains("WhenHasSomePropertyName"));When(...)怎么用最好?
      【解决方案3】:

      您需要使用上下文绑定。我通常使用具体的“目标”类来决定内核将使用.WhenInjectedInto().WhenInjectecExactlyInto() 提供哪个服务实现。

      【讨论】:

      • 如果目标类有一个属性名就绑定:Bind&lt;IMessageService&gt;().To&lt;MailingService&gt;().When(request =&gt; (((System.Reflection.PropertyInfo[])((System.Reflection.TypeInfo)((request.Target.Member).ReflectedType)).DeclaredProperties)[0]).Name.Contains("WhenHasSomePropertyName"));你怎么用When(...)你能举个例子最好的用法是什么?
      最近更新 更多