依赖注入,ASP.NET MVC,Ninject:将某些实现绑定到某些控制器

Dependency Injection, ASP.NET MVC, Ninject: Binding certain implementations to certain controllers

假设我有两个控制器,它们在构造函数中使用相同的接口,例如:

public class XController: Controller{

   private IOperation operation;
   public XController (IOperation operation){
      this.operation = operation;
   }

   public ActionResult Index(){
       ViewBag.Test = operation.Test();
       return View();
   } 
}

public class YController: Controller{

   private IOperation operation;
   public YController (IOperation operation){
      this.operation = operation;
   }

   public ActionResult Index(){
       ViewBag.Test = operation.Test();
       return View();
   } 
}

public interface IOperation {
    String Test();
}
public class Implementation1: IOperation{
    String Test(){retrun "Implementation 1";}
}
public class Implementation2: IOperation{
    String Test(){retrun "Implementation 2";}
}

使用 Ninject 时,我可以执行 kernel.Bind<IOperation>().To<Implementation1>(),这会改变我的 X 和 Y 控制器的行为。但是,有时我可能需要将我的 X 控制器绑定到 Implementtaion1,同时让我的 Y 控制器仍然绑定到 Implementation 2。 这是否可能完全不必通过定义新接口将实现 1 与实现 2 完全分开?

您可以像这样使用条件/contextual bindings

Bind<IOperation>().To<Implementation1>()
    .WhenInjectedInto<Controller1>();

Bind<IOperation>().To<Implementation2>()
    .WhenInjectedInto<Controller2>();

请注意,然后 WhenInjectedInto 约束会检查 直接 注入的类型。还有一些其他内置约束,当然您也可以使用 When(...) 方法编写自己的约束。