【问题标题】:Error "CommentsController does not have a default constructor"错误“CommentsController 没有默认构造函数”
【发布时间】:2012-07-14 19:07:45
【问题描述】:

问题: 我正在使用 MVC4 WebAPI 并在 Get() 调用期间抛出错误。

错误:

System.ArgumentException:类型“Comments2.Controllers.CommentsController”没有默认构造函数

堆栈跟踪:

at System.Linq.Expressions.Expression.New(Type type)
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}

我很乐意提供所需的任何代码,只需让我知道您想看到什么。

控制器:

namespace Comments2.Controllers 
{
    //[Authorize]
    public class CommentsController : ApiController 
    {
        ICommentRepository repository;

    public CommentsController(ICommentRepository repository) 
    {
        this.repository = repository;
    }

    [Queryable]
    public IQueryable<Comment> GetComments()
    {
        return repository.Get().AsQueryable();
    }

    public Comment GetComment(int id)
    {
        Comment comment;
        if (!repository.TryGet(id, out comment))
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        return comment;
    }
}

JavaScript:

$(function() {
    $("#getComments").click(function () {
        // We're using a Knockout model. This clears out the existing comments.
        viewModel.comments([]);

        $.get('/api/comments', function (data) {
            // Update the Knockout model (and thus the UI) with the comments received back 
            // from the Web API call.
            viewModel.comments(data);
        });

    });
});

【问题讨论】:

  • 您是否正确设置了 DI 容器,并从应用程序开始启动它?您是否配置了要注入的 ICommentRepository 实例?
  • 我没有。使用 Unity 或 Ninject 会更好吗?这些是我唯一有兴趣使用的两个,我了解 IoC 和 DI 的概念,但我正在尝试学习将它与 MVC4 和 WebAPI 一起使用...我只是通过 NuGet 添加它吗?

标签: c# javascript asp.net-mvc-4 asp.net-web-api


【解决方案1】:

看起来你正在使用 HttpControllerActivator 的默认实现,它不适用于依赖注入。试试this,它集成了统一容器来处理依赖关系,但你可以修改它以使用你想要的任何 DI 实现。

【讨论】:

  • 为什么要投反对票? DefaultHttpControllerActivator 只需要默认构造函数,因此您必须创建自己的,最干净的解决方案是 DI 容器。
  • Rafal 的回答中提供的链接帮助引导我朝着正确的方向前进。
  • 由于链接可能会失效,因此鼓励答案在答案中包含解决方案的相关信息。如果链接的内容被删除或更改,则答案对于以后发现此问题的其他人将毫无用处。这可能就是为什么有人(不是我)投反对票的原因,尽管在不评论原因的情况下投反对票是一种不好的形式。
  • @Zaphod,是的,但它的内部 SO 链接与您在问题被关闭为重复时获得的链接相同。
  • @Rafal 我没有说它是正确的,只是为什么它可能被否决了 :-) 在我看来内部 SO 链接没问题...
【解决方案2】:

我不确定您使用的是什么 IOC 容器,我个人使用 Ninject,here 是我用来使其正常工作的说明。

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    相关资源
    最近更新 更多