2012-07-15 25 views
16

问题: 我正在使用MVC4 WebAPI,并在Get()调用期间抛出错误。错误“CommentsController没有默认构造函数”

错误:

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

我很高兴地给简直让我知道你想看看有什么需要的任何代码。

控制器:

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

    }); 
}); 
+1

您是否正确设置了DI容器,并从应用程序启动启动它?你配置了一个ICommentRepository的实例来注入吗? – 2012-07-15 21:39:06

+0

我没有。用户Unity或Ninject会更好吗?这些是我感兴趣使用的唯一两个,我理解IoC和DI的概念,但我试图学习如何使用它与MVC4和WebAPI ...我只是通过NuGet添加? – 2012-07-15 21:47:00

回答

6

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

+0

为什么选择投票? DefaultHttpControllerActivator只需要默认的构造函数,所以你必须创建你自己的,最干净的解决方案就是DI容器。 – Rafal 2012-07-16 04:01:17

+0

在拉法尔的回答中提供的链接可以帮助我指引正确的方向。 – 2012-07-16 05:52:42

+0

由于链接可能会死亡,所以SO鼓励在答案中包含解决方案的相关信息。如果链接的内容被删除或更改,那么对于稍后发现此问题的其他人来说,答案将毫无用处。这可能就是为什么有人投了票(不是我),尽管这是不好的投票方式,但没有评论为什么。 – Zaphod 2017-01-12 18:17:19

1

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