运行时控制器中的无参数构造函数错误

时间:2015-07-22 08:29:00

标签: asp.net asp.net-mvc asp.net-mvc-4 dependency-injection controller

我收到无参数构造函数错误。当我只将Service层实例传递给构造函数时,我的代码运行正常 -

   public class ProjectController : Controller
    {
     private readonly IProjectService _projectService; 
     public ProjectController(IProjectService projectService)
    {
        this._projectService = projectService;
    }

然后我的所有行动方法都在他们之下。 当我想在控制器中使用其他接口时出现问题,所以我尝试了类似的东西---

  public class ProjectController : Controller
   {
    private readonly IProjectService _projectService;
    private readonly ICityService _cityService;
    private readonly ILocalityService _localityService;
    public ProjectController(IProjectService projectService)
    {
        this._projectService = projectService;
    }
    public ProjectController(ICityService cityService)
    {
        this._cityService = cityService;
    }
    public ProjectController(ILocalityService localityService)
    {
        this._localityService = localityService;
    } 

通过这种方式,我也能够使用其他接口中定义的方法。在编译时,我认为一切都会正常工作,但现在我收到了这个错误。我想知道我的方法是错的吗?我应该怎么做,以便我可以使用服务层中的给定接口及其方法。我已将完整代码粘贴到http://pastebin.com/fspycG5p

1 个答案:

答案 0 :(得分:2)

您需要创建一个接受所有接口的构造函数,而不是带有单个接口的几个构造函数。

 public class ProjectController : Controller
 {
    private readonly IProjectService _projectService;
    private readonly ICityService _cityService;
    private readonly ILocalityService _localityService;

    public ProjectController(IProjectService projectService, 
                             ICityService cityService, 
                             ILocalityService localityservice)
    {
        this._projectService = projectService;
        this._cityService = cityService;
        this._localityService = localityService;
    }
}

这假设您已正确配置了其余的IOC。