c# - 错误 "CommentsController does not have a default constructor"

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

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

错误:

System.ArgumentException: Type 'Comments2.Controllers.CommentsController' does not have a default constructor

堆栈跟踪:

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)"}

我很乐意提供所需的任何代码,只需告诉我您想看到的内容即可。

Controller :

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);
        });

    });
});

最佳答案

它看起来就像你正在使用 HttpControllerActivator 的默认实现,它不能与依赖注入(inject)一起工作。尝试 this它集成了统一容器来处理依赖关系,但您可以修改它以使用您想要的 DI 的任何实现。

关于c# - 错误 "CommentsController does not have a default constructor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11495776/

相关文章:

c# - 如何在单选按钮列表中的正确站点上设置文本

c# - 使用 Collat​​ionInfo.Comparer 在 c# 和 SQL 之间实现一致排序

javascript - 在 js 中使用 getElementsByTagName 时收到错误消息

mysql - 在 mysql 中使用简单的成员资格提供程序

c# - 从 DOMAIN\Username c# 中提取用户名

c# - 如何通过组合其他两个列表来创建新列表?

javascript - 两个不同的切片的两个不同的分割

javascript - Bootstrap toggle with chevron 在生产和本地工作不同

asp.net-mvc-4 - 更改 [DataType.Currency] 呈现 html 的方式

c# - 动态 Linq 按变量排序