Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "CommentsController does not have a default constructor"

Problem: I'm using MVC4 WebAPI and am throwing an error during a Get() call.

Error:

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)"}

I'm happy to give any code required simply let me know what you'd like to see.

Controller:

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

    });
});
like image 387
Computer Guy Avatar asked Jul 15 '12 21:07

Computer Guy


2 Answers

It seams like you are using default implementation of HttpControllerActivator which will not work with dependency injection. Try this it integrates unity container to handle dependency but you can modify it to use any implementation of DI you want.

like image 158
Rafal Avatar answered Nov 12 '22 10:11

Rafal


I'm not sure what IOC Container you are using, I personally use Ninject and here are the instructions I use to get this working properly.

like image 1
bkorzynski Avatar answered Nov 12 '22 08:11

bkorzynski