是否可以将不同的接口绑定到实现所有接口的同一个实例?

时间:2012-04-18 08:56:32

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

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

interface IAmAnInterface
{
    void DoSomething();
}

interface IAmAnInterfaceToo
{
    void DoSomethingElse();
}

和一个实现两者的类:

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

    public void DoSomething()
    {
    }

    public void DoSomethingElse()
    {
    }
}

现在我使用Ninject将同一个类绑定到两个接口。由于我希望IAmAnImplementation使用IAmAnInterface以及IAmAnInterfaceToo相同实例,因此很明显我需要某种单例。我和ninject.extensions.namedscope以及InScope()一起玩,但没有成功。我的最后一次尝试是:

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

但不幸的是,当我通过kernel.Get<IDependOnBothInterfaces>();请求我的测试类的实例时,它实际上使用了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对IAmAnImplementation以及IAmAnInterface使用相同的IAmAnInterfaceToo实例?

1 个答案:

答案 0 :(得分:101)

使用V3.0.0很容易

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