【发布时间】:2012-07-14 19:07:45
【问题描述】:
问题: 我正在使用 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);
});
});
});
【问题讨论】:
-
您是否正确设置了 DI 容器,并从应用程序开始启动它?您是否配置了要注入的 ICommentRepository 实例?
-
我没有。使用 Unity 或 Ninject 会更好吗?这些是我唯一有兴趣使用的两个,我了解 IoC 和 DI 的概念,但我正在尝试学习将它与 MVC4 和 WebAPI 一起使用...我只是通过 NuGet 添加它吗?
标签: c# javascript asp.net-mvc-4 asp.net-web-api