首页 文章

可以将接口绑定到特定类中的类型吗?

提问于
浏览
1

Ninject(最新版本)可以将接口绑定到特定类中的类型吗?我的意思是......让我说我有两个 class ..

ClassA和ClassB都在构造函数中有IContext注入..可以说类型IContext到ContextA的ClassA和IContext到ContextB到ClassB?

2 回答

  • 1

    您也可以使用条件绑定而不是使用命名绑定,这需要更少的代码并且更安全:

    Bind<IContext>().To<ContextA>().WhenInjectedInto<SomeClassThatNeedsAContext>();
    Bind<IContext>().To<ContextB>().WhenInjectedInto<SomeOtherClassThatNeedsBContext>();
    
  • 3

    一种方法是使用命名绑定 .

    kernel.Bind<IContext>().To<ContextA>().Named("A");
    kernel.Bind<IContext>().To<ContextB>().Named("B");
    
    kernel.Bind<SomeClassThatNeedsContext>().ToSelf().WithConstructorArgument("context",ninjectContext=>ninjectContext.Get<IContext>("A"));
    kernel.Bind<SomeOtherClassThatNeedsContext>().ToSelf().WithConstructorArgument("context",ninjectContext=>ninjectContext.Get<IContext>("B"));
    

    另一种方法可能是单独使用“WithConstructorArgument”

    kernel.Bind<SomeClassThatNeedsAContext>().ToSelf().WithConstructorArgument("context",ninjectContext=>ninjectContext.Get<ContextA>());
    

    为了避免混淆,Ninject也有上下文的概念,不要将它与你提供的示例IContext等混淆 .

    我从经验中发现的一件事是,经常如果我发现自己这样做,我的界面或类设计中存在一个缺陷 . 也许你真的需要两个不同的接口?

相关问题