17

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

    });
});
4

2 回答 2

7

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

于 2012-07-15T21:51:06.550 回答
1

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

于 2013-05-28T15:48:30.683 回答