依赖注入:-尝试创建 'controller' 类型的控制器时发生错误

Dependency injection :-An error occurred when trying to create a controller of type 'controller'

控制器:

private readonly IService _service;

public DisplayController(IService service)
{
    _service = service;
}

public ActionResult Index(int resultid)
{

    var response = _service.GetQuizResults(resultid);

    var alltheresults = Mapper.Map<Services.Contracts.Model.Quiz, Quiz>(response);

    return View(alltheresults);
}

错误:

InvalidOperationException: An error occurred when trying to create a controller of type 'Travelers.eBusiness.RiskQuiz.Web.Controllers.DisplayController'. Make sure that the controller has a parameterless public constructor

经过大量谷歌搜索后,我确实添加了另一个构造函数:

public DisplayController()
{

}

确实解决了错误,但是 _service 变为空。

Unity 似乎无法找到 IService 的注册实现,因此无法创建控制器的实例。它当然可以使用您刚刚添加的无参数构造函数创建一个,但是它不会注入 IService.

的实例

您必须在应用程序启动时注册 IService 它的实现并删除无参数构造函数。

参见:setting up the Unity container