2017-06-03 107 views
0

我是新来的构造函数请解释为什么它给我下面的错误:“出错确保控制器具有一个无参数的公共构造

"An error occurred when trying to create a controller of type 'HomeController'. Make sure that the controller has a parameterless public constructor. 

这里我有1接口(IRepo)1类文件(回购) IRepo.cs

public interface IRepo 
    { 
     IEnumerable<Employee> GetEmployee(); 
     IQueryable<Employee> GetEmployee(int id); 
    } 

Repo.cs

Ctxdb _db = null; 
     public Repo(Ctxdb db) 
     { 
      this._db = db; 
     } 

     public IEnumerable<Employee> GetEmployee() 
     { 
      // 
     } 

HomeController.cs

IRepo _ObjRepo = null; 

     public HomeController(Repo ObjRepo) 
     { 

      _ObjRepo = ObjRepo; 
     } 

     [Route("GetEmp")] 
     [HttpGet] 
     public IHttpActionResult GetDat() 
     { 
      var x = _ObjRepo.GetEmployee(); 
      if (x != null) 
       return Content(HttpStatusCode.OK, x); 
      else 
       return Content(HttpStatusCode.BadRequest,"Not Implemented"); 
     } 
+0

只是在你的控制器中有一个无参数的构造函数。 –

+0

但是,即时通讯管理它可能你plz给我任何提示 – Hussain

+1

这很清楚:你需要创建一个没有参数的公共构造函数...例如:'公共HomeController()'还有很多问题的答案,谈话关于这个问题。请参考这些帖子 –

回答

4

看起来你wan't实现依赖注入。如果这是正确的应该比你做三个吊环:

  1. 更改您的构造函数使用的IRepo代替Repo
  2. 安装和配置IoC容器像AutoFac或Unity
  3. 配置的ASP.NET Web API的依赖解析器

official docs有一个很好的教程。

相关问题