17

問題: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);
        });

    });
});
4

2 に答える 2

7

依存性注入では機能しないHttpControllerActivatorのデフォルトの実装を使用しているように見えます。これを試してみてください。ユニティコンテナを統合して依存関係を処理しますが、必要なDIの実装を使用するように変更できます。

于 2012-07-15T21:51:06.550 に答える
1

使用しているIOCコンテナがわかりません。私は個人的にNinjectを使用しています。これを正しく機能させるために使用する手順は、次のとおりです。

于 2013-05-28T15:48:30.683 に答える