0

I am trying to call in to a repository method to fetch some data, which be returned from a Web Api 'Get' request.

public class BookRepository : IBookRepository
{
    public Book GetBookInfo()
    {
        return new Book
        {
            Title = "Book1",
            Chapters = new List<string>
                  {
                      "Chapter1",
                      "Chapter2",
                      "Chapter3",
                      "Chapter4"
                  }
        };

My apicontroller:

public class BooksController : ApiController
{
    private readonly IBookRepository _repository;

    public BooksController () { }

    public BooksController (IBookRepository repository)
    {
        this._repository = repository;
    }

    // GET api/books
    public Book Get()
    {
        return _repository.GetBookInfo();
    }

The issue is that when I navigate to this in the browser e.g. 'http://localhost:49852/api/books' I am getting a NullReferenceException. Please can you explain why and how to rectify?

1
  • How are you injecting repository on BooksController constructor? Commented Feb 4, 2015 at 21:36

2 Answers 2

1

I don't think your constructor injection is hooked up correctly. Can you show us the code where you set the HttpConfiguration.DependencyResolver? Assuming that you haven't hooked this up correctly, when the Controller is instantiated, the default Constructor is called, and therefore _repository is null.

To test this out, change your default constructor to create an instance of BookRepository. i.e.

public BookController()
{
    _repository = new BookRepository();
}
Sign up to request clarification or add additional context in comments.

Comments

0

your mostly likely not instantiating your Repository, your default constructor

public BooksController () { }

does not create a new instance of your repository. You have two options:

  1. change the default constructor to:

    public BooksController () 
    {
        _repository = new BookRepository();
    }
    
  2. use a DI container to Resolve the IBookRepository. Here is an example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.