[英]How to inject multiple dependencies into controller?
我正在使用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)
}
我在这里注入多个依赖(服务)对象控制器的构造函数。 和单元测试方法的工作由该well.But当我运行应用程序,它不工作。
它给出“错误500”。
我想知道如果您有多个依赖项并且想要将这些依赖项注入到controller。我们需要单独注入还是可以一次注入(就像我上面所做的那样),我们应该怎么做。
下面是使用System.Web.Mvc的Bootstrapper文件代码; 使用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>();
}
}
您需要确保解决需要的东西,以便Unity在顶层注入东西,一旦完成此操作,就不应再次明确使用container
。 检查您是这样创建的:
_productController = container.Resolve<IProductController>();
另外,您也应该向Unity注册ProductController
。
container.RegisterType<IProductController, ProductController>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.