错误“CommentsController没有默认构造函数”

时间:2012-07-15 21:32:08

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

问题: 我正在使用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);
        });

    });
});

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

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

相关问题