"尝试创建'HomeController'类型的控制器时发生错误.确保控制器具有无参数的公共构造函数

Hus*_*ain 0 c# asp.net-web-api

我是建筑师的新手.请解释为什么它给我以下错误:

"An error occurred when trying to create a controller of type 'HomeController'. Make sure that the controller has a parameterless public constructor.
Run Code Online (Sandbox Code Playgroud)

这里我有1个接口(IRepo)1类文件(Repo)IRepo.cs

public interface IRepo
    {
        IEnumerable<Employee> GetEmployee();
        IQueryable<Employee> GetEmployee(int id);
    }
Run Code Online (Sandbox Code Playgroud)

Repo.cs

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

        public IEnumerable<Employee> GetEmployee()
        {
           //  
        }
Run Code Online (Sandbox Code Playgroud)

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");
        }
Run Code Online (Sandbox Code Playgroud)

And*_*mer 6

看起来你不想实现依赖注入.如果这是正确的,你应该做三件事:

  1. 将构造函数更改为使用IRepo而不是Repo
  2. 安装和配置AutoFac或Unity等IoC容器
  3. 配置ASP.NET Web API依赖性解析程序

官方文档中有一个很棒的教程.