【问题标题】:How to inject multiple dependencies in constructor?如何在构造函数中注入多个依赖项?
【发布时间】:2014-05-02 13:23:23
【问题描述】:

我正在做单元测试。我有一个依赖于多个存储库的控制器(意味着有多个依赖项)。

下面是控制器的一段代码:-

public class TestController : BaseController
{
  //Declaring dependencies 
   private IProductService _productService;
   private IStudenctService _studentService;
   private ITeacherService _teacherService;
   private IClassService _classService;
   private ITaxService _taxService;
   private ICategoryService _categoryService;
   private ISchoolService _schoolService;
  //Constructor calling…
   public TestController ()
   {

   }

   public TestController (IProductService productService)
   {
       this._ productService = productService;
   }
   public TestController (IStudenctService studenctService)
   {
       this._ studentService = studenctService;
   }
   public TestController (ITeacherService teacherService)
   {
       this._ teacherService = teacherService;
   }
   public TestController (IClassService classService)
   {
       this._ classService = classService;
   }
   public TestController (ITaxService taxService)
   {
       this._ taxService = taxService;
   }
   public TestController (ICategoryService categoryService)
   {
       this._ categoryService = categoryService;
   }
   public TestController (ISchoolService schoolService)
   {
       this._ schoolService = schoolService;
   }
  public TestController (ISchoolService schoolService, ICategoryService categoryService)
   {
       this._ schoolService = schoolService;
       this._ categoryService = categoryService;
   }
   public TestController (ISchoolService schoolService, ICategoryService categoryService, ITaxService taxService, IClassService classService)       {
       this._ schoolService = schoolService;
       this._ categoryService = categoryService;
       this._ taxService = taxService;
       this._ classService = classService;
   }
}

在上面的代码中,我为每个依赖项创建了单独的构造函数。其中有 2 个构造函数采用多个参数(依赖项 arg)。

通过这种方式,我的单元测试方法运行良好。但是当我运行应用程序时,它给了我以下错误:-

呃-哦,出了点问题!错误代码:500

但是当我只调用一个参数构造函数时,它就可以工作了。谁能告诉我这里出了什么问题?多依赖怎么办?

【问题讨论】:

  • 错误代码500与Unity无关我认为错误不是来自depeandecy注入错误应该在其他地方
  • 配置 Visual Studio 以中断所有异常(通过转到 Debug/Exceptions... 并选中“Common Language Runtime Exceptions”行的“Thrown”和“User-unhandled”复选框)看看弹出了什么确切的异常。始终在您的问题中发布异常详细信息。

标签: c# unit-testing dependency-injection unity-container


【解决方案1】:

如果这些是您的类的依赖项,那么您应该有一个将所有依赖项作为参数的构造函数。

换句话说,如果没有所有依赖项,您就无法实例化到有效状态。它们不是可选的,它们是依赖项

我会先采用这种方法,然后再问一个单独的问题,如果您的应用程序仍然抛出错误。

【讨论】:

  • ,最初我使用了这种方法(只有一个具有所有依赖项的构造函数)但是在调用该控制器时它给出了同样的错误。但是单元测试做得很好。
  • 我完全同意。应该有always only be one constructor
  • @Pawan 在您发布的代码中,有一个默认(无参数)构造函数。这使我认为您可能没有实现自己的控制器工厂。 (也就是说,如果你的类有依赖,并且定义了一个构造函数来传递它们,那么它不应该有一个无参数的构造函数,因为这些依赖将被初始化为null。)实现细节控制器工厂可以在这里找到:weblogs.asp.net/shijuvarghese/archive/2008/10/10/…
猜你喜欢
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 2018-06-17
  • 2021-09-08
  • 2020-10-24
  • 2019-04-20
相关资源
最近更新 更多