2012-07-15 99 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是我用來正確工作的說明。

相關問題