0
我正在使用Unity庫來使用依賴注入。我有一個控制器(產品)和下面是構造代碼如何向控制器注入多個依賴關係?
public ProductController(IService1 ser1,IService2 ser2,IService3 ser3,IService4 ser4)
{
this._Service1 = ser1;
this._Service2 = ser2;
this._Service3 = ser3;
this._Service4 = ser4;
}
並在下面這controller.Which單元測試代碼被注入上面的4個服務類對象到該控制器的構造函數。
ProductController _productController;
Mock<IService1> _ser1Mock;
Mock<IService2> _ser2Mock;
Mock<IService3> _ser3Mock;
Mock<IService4> _ser4Mock;
if(_productController!=null)
{
_productController = new ProductController(
_ser1Mock.Object,_ser2Mock.Object,_ser3Mock.Object,_ser4Mock.Object)
}
在這裏,我注入多個依賴關係(服務)對象控制器的構造函數。單元測試方法運行良好。但是,當我運行應用程序時,它不工作。
它給'錯誤500'。
我想知道我們應該怎麼做,如果你有多個依賴關係,你想注入這些依賴關係到controller.Do我們需要單獨注入或者我們可以注入一次(就像我上面做的那樣)。
以下是使用System.Web.Mvc的引導程序文件代碼 ; 使用Microsoft.Practices.Unity;使用Unity.Mvc4的 ;
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(
new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IService1Dal,Service1Dal>();
container.RegisterType<IService1,Service1>();
container.RegisterType<IService2Dal,Service2Dal>();
container.RegisterType<IService2,Service2>();
container.RegisterType<IService3Dal,Service3Dal>();
container.RegisterType<IService3,Service3>();
container.RegisterType<IService4Dal,Service4Dal>();
container.RegisterType<IService4,Service4>();
}
}
,據我所知,你是不是注射什麼,你只是調用構造函數 – thumbmunkeys
向我們展示您的Unity配置(XML或Fluent)。這可能是問題所在。另外,WHERE /你是如何注入/解析?不希望調用'new ProductController'! – Belogix
@ Belogix,我已經更新了配置代碼。 – Pawan