javascript 错误“CommentsController 没有默认构造函数”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11495776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error "CommentsController does not have a default constructor"
提问by Computer Guy
Problem: I'm using MVC4 WebAPI and am throwing an error during a Get() call.
问题:我正在使用 MVC4 WebAPI 并且在 Get() 调用期间抛出错误。
Error:
错误:
System.ArgumentException: Type 'Comments2.Controllers.CommentsController' does not have a default constructor
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)"}
I'm happy to give any code required simply let me know what you'd like to see.
我很乐意提供所需的任何代码,只需让我知道您想看到什么。
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:
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);
});
});
});
采纳答案by Rafal
It seams like you are using default implementation of HttpControllerActivator which will not work with dependency injection. Try thisit integrates unity container to handle dependency but you can modify it to use any implementation of DI you want.
看起来你正在使用 HttpControllerActivator 的默认实现,它不适用于依赖注入。试试这个它集成了统一容器来处理依赖,但你可以修改它以使用你想要的任何 DI 实现。