2012-07-15 20 views
16

問題: MVC4 WebAPIを使用していて、Get()呼び出し中にエラーが発生しています。エラー "CommentsControllerにデフォルトのコンストラクタがありません"

エラー:

System.ArgumentException: Type 'Comments2.Controllers.CommentsController' does not have a default constructor

のStackTrace:

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を:あなたは依存性の注入では動作しません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です。

関連する問題