問題: 我正在使用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