问题: 我正在使用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);
});
});
});
您是否正确设置了DI容器,并从应用程序启动启动它?你配置了一个ICommentRepository的实例来注入吗? – 2012-07-15 21:39:06
我没有。用户Unity或Ninject会更好吗?这些是我感兴趣使用的唯一两个,我理解IoC和DI的概念,但我试图学习如何使用它与MVC4和WebAPI ...我只是通过NuGet添加? – 2012-07-15 21:47:00