Ошибка "CommentsController не имеет конструктора по умолчанию" - программирование
Подтвердить что ты не робот

Ошибка "CommentsController не имеет конструктора по умолчанию"

Проблема: Я использую MVC4 WebAPI и бросаю ошибку во время вызова Get().

Ошибка:

System.ArgumentException: Type 'Комментарии2.Controllers.CommentsController' не имеет конструктора по умолчанию

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:

$(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);
        });

    });
});
4b9b3361

Ответ 1

Это похоже на то, что вы используете стандартную реализацию HttpControllerActivator, которая не будет работать с инъекцией зависимостей. Попробуйте this, он интегрирует контейнер единиц для обработки зависимости, но вы можете изменить его, чтобы использовать любую реализацию DI, которую вы хотите.

Ответ 2

Я не уверен, что вы используете IOC Container, я лично использую Ninject и здесь - это инструкции, которые я использую для правильной работы.