Paolo B
Paolo B

Reputation: 3354

Web Api returning NullReferenceException using repository

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?

Upvotes: 0

Views: 1105

Answers (2)

Omar Elabd
Omar Elabd

Reputation: 1934

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

Upvotes: 0

failedprogramming
failedprogramming

Reputation: 2522

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

Upvotes: 1

Related Questions