【问题标题】:Is it possible to bind different interfaces to the same instance of a class implementing all of them?是否可以将不同的接口绑定到实现所有这些接口的类的同一个实例?
【发布时间】:2012-04-29 16:00:58
【问题描述】:

我有以下(简化的)情况:我有两个接口

interface IAmAnInterface
{
    void DoSomething();
}

interface IAmAnInterfaceToo
{
    void DoSomethingElse();
}

以及实现两者的类:

class IAmAnImplementation: IAmAnInterface, IAmAnInterfaceToo
{
    public IAmAnImplementation()
    {
    }

    public void DoSomething()
    {
    }

    public void DoSomethingElse()
    {
    }
}

现在我使用 Ninject 将同一个类绑定到两个接口。因为我想要IAmAnImplementation相同实例 用于IAmAnInterfaceIAmAnInterfaceToo,很明显我需要某种单例。我玩过ninject.extensions.namedscopeInScope(),但没有成功。我最后一次尝试是:

Bind<IAmAnImplementation>().ToSelf().InSingletonScope();
Bind<IAmAnInterface>().To<IAmAnImplementation>().InSingletonScope();
Bind<IAmAnInterfaceToo>().To<IAmAnImplementation>().InSingletonScope();

但不幸的是,当我通过 kernel.Get&lt;IDependOnBothInterfaces&gt;(); 请求测试类的实例时,它实际上使用了不同的 IAmAnImplementation 实例。

class IDependOnBothInterfaces
{
    private IAmAnInterface Dependency1 { get; set; }
    private IAmAnInterfaceToo Dependency2 { get; set; }

    public IDependOnBothInterfaces(IAmAnInterface i1, IAmAnInterfaceToo i2)
    {
        Dependency1 = i1;
        Dependency2 = i2;
    }

    public bool IUseTheSameInstances
    {
        get { return Dependency1 == Dependency2; } // returns false
    }
}

有没有办法告诉 Ninject 为 IAmAnInterfaceIAmAnInterfaceToo 使用相同的 IAmAnImplementation 实例?

【问题讨论】:

标签: c# dependency-injection inversion-of-control ninject ninject-3


【解决方案1】:

使用V3.0.0非常容易

Bind<I1, I2, I3>().To<Impl>().InSingletonScope();

【讨论】:

  • +1 谢谢。事实上我使用的是 3.0,所以我会选择这个解决方案。
  • 如果你有4个以上的接口:Bind(I1, I2, I3, I4, I5).To&lt;Impl&gt;().InSingletonScope();
  • 您能否解释一下这需要如何与上述场景集成?
  • 当你在编译时知道所有接口时这很好,但当你需要在运行时扫描它们时就不那么好了。
  • 啊,伙计,我有两个绑定而不是多个接口,这导致每个接口只有一个单例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
相关资源
最近更新 更多