小编Sil*_*las的帖子

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

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

interface IAmAnInterface
{
    void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

interface IAmAnInterfaceToo
{
    void DoSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)

和一个实现两者的类:

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

    public void DoSomething()
    {
    }

    public void DoSomethingElse()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我使用Ninject将同一个类绑定到两个接口.因为我想要使用相同IAmAnImplementationbeeing 实例,IAmAnInterface而且IAmAnInterfaceToo很明显我需要某种单例.我和ninject.extensions.namedscope一起,InScope()但没有成功.我的最后一次尝试是:

Bind<IAmAnImplementation>().ToSelf().InSingletonScope();
Bind<IAmAnInterface>().To<IAmAnImplementation>().InSingletonScope();
Bind<IAmAnInterfaceToo>().To<IAmAnImplementation>().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)

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

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

    public IDependOnBothInterfaces(IAmAnInterface i1, …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection ninject inversion-of-control ninject-3

38
推荐指数
1
解决办法
5938
查看次数