【问题标题】:"An error occurred when trying to create a controller of type 'HomeController'. Make sure that the controller has a parameterless public constructor“尝试创建“HomeController”类型的控制器时发生错误。确保控制器具有无参数的公共构造函数
【发布时间】:2017-06-03 10:55:16
【问题描述】:

我是构造函数的新手。请解释为什么它给我以下错误:

"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 个类文件 (Repo) 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");
        }

【问题讨论】:

  • 只在你的控制器中有一个无参数的构造函数。
  • 但是我很困惑,你能不能给我任何提示
  • 这很清楚:您需要创建一个不带参数的公共构造函数...示例:public HomeController()此外,有很多问题的答案都在谈论这个问题。请参考这些帖子
  • 是的,我创建了 public HomeController(Repo ObjRepo) { _ObjRepo = ObjRepo; } 以这种方式,但我怎么能调用它

标签: c# asp.net-web-api


【解决方案1】:

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

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

official docs 中有一个很棒的教程。

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 2019-04-13
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多