接口与ninject多个实现

接口与ninject多个实现

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

问题描述

我有一个有两个不同实现的接口。

I've got an interface that has two different implementations.

public interface IProducer
{
}

public class Producer : IProducer
{
}

public class FaultProducer : IProducer
{
}

我有两个不同的类,都以IProducer作为依赖。

I have two different classes that both take an IProducer as a dependency.

public class ConsumerChannel
{
    public ConsumerChannel(IProducer producer)
    {
    }
}

public class TradePublisher
{
    public TradePublisher(IProducer producer)
    {
    }
}

TradePublisher 需要生产者和 ConsumerChannel 需要 FaultProducer 。我只能绑定 IProducer 到一个实现。在Windsor我可以这样做与命名绑定和 Dependency.OnComponent 但我不能在Ninject中找到类似的能力。有没有办法注入Ninject中的特定依赖项?

TradePublisher needs a Producer and ConsumerChannel needs a FaultProducer. I can only bind IProducer to one implementation. In Windsor I could do this with named bindings and Dependency.OnComponent but I can't find similar abilities in Ninject. Is there a way to inject specific dependencies in Ninject?

推荐答案

使用:

Bind<IProducer>().To<FaultProducer>().Named("FaultProducer");

public TradePublisher([Named("FaultProducer")] IProducer producer)
    //...
}

这篇关于接口与ninject多个实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:45