2012-07-15 5 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; 
    } 
} 

자바 스크립트 : 당신은 의존성 주입 작동하지 않습니다 HttpControllerActivator의 기본 구현을 사용하는 것처럼

$(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의 인스턴스를 구성 했습니까? –

+0

나는 그렇지 않다. Unity 또는 Ninject를 사용하는 것이 더 좋을까요? 그것들은 제가 사용하고자하는 유일한 두 가지입니다, IoC와 DI의 개념을 이해 합니다만 MVC4와 WebAPI와 함께 사용하는 법을 배우려고합니다 ... 그냥 NuGet을 통해 추가합니까? –

답변

6

그것은 솔기. this을 사용해보십시오. 단일성 컨테이너를 통합하여 종속성을 처리하지만 원하는 DI 구현을 사용하도록 수정할 수 있습니다.

+0

왜 투표가 실패합니까? DefaultHttpControllerActivator는 단순히 기본 생성자를 필요로하므로 자신 만의 생성자를 만들어야하며 가장 깨끗한 솔루션은 DI 컨테이너입니다. – Rafal

+0

Rafal의 응답 도움말에 제공된 링크를 통해 올바른 방향으로 안내 할 수 있습니다. –

+0

링크가 사라질 수 있으므로 SO는 답안에서 솔루션의 관련 정보를 포함하도록 답을 권장합니다. 링크 된 내용이 제거되거나 변경되면 나중에 찾은 다른 사용자에게는 대답이 쓸모 없게됩니다. 그 이유에 대해 언급하지 않고 투표하기에 좋지 않은 방식이지만 누군가 투표를 한 이유가 될 수 있습니다. – Zaphod

1

사용중인 IOC 컨테이너가 무엇인지 잘 모르겠습니다. 개인적으로 Ninject를 사용하고 here을 올바르게 사용하기위한 지시 사항입니다.

관련 문제