我想将多个具体类绑定到Ninject中的接口

时间:2012-01-10 13:51:18

标签: asp.net-mvc-3

我想将多个具体类绑定到Ninject中的接口。

我有 ITestService 界面和具体实施 TestServiceA TestServiceB

他们受到这样的约束:

kernel.Bind<ITestService>().To<TestServiceA>();
kernel.Bind<ITestService>().To<TestServiceB>();

在“ HomeController(ITestService服务)”中,我有这个:

private ITestService _service;  

public HomeController(ITestService service) 
{   
     _service = service 
}

public ActionResult Index() 
{   
     ViewBag.Message = _service.GetMessage();
     return View(); 
} 

它引发了一个错误。我该如何解决?

1 个答案:

答案 0 :(得分:4)

那不行。您将两个东西绑定到同一个接口,Ninject无法知道要实现哪个具体类。 Ninject offers contextual binding虽然。{/ p>

一个例子:

// Setup your bindings with a name:
Bind<ITestService>().To<TestServiceA>().Named("A");
Bind<ITestService>().To<TestServiceB>().Named("B");


// Then in your controller, specify the name with an attribute:
public HomeController([Named("A")]ITestService service)
{   
     _service = service 
}