首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >错误"CommentsController没有默认构造函数“

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

Stack Overflow用户
提问于 2012-07-16 05:32:08
回答 2查看 16.2K关注 0票数 17

问题:我正在使用MVC4 WebAPI,并且在Get()调用过程中抛出错误。

错误:

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

StackTrace:

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

    });
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-16 05:51:07

它看起来像是你在使用HttpControllerActivator的默认实现,它不能与依赖注入一起工作。试试this,它集成了unity容器来处理依赖,但你可以修改它来使用你想要的任何DI实现。

票数 7
EN

Stack Overflow用户

发布于 2013-05-28 23:48:31

我不确定您使用的是什么IOC容器,我个人使用的是Ninject和here,这是我用来让它正常工作的指令。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11495776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档