Null reference exception when tried to run dependency injection

4.3k views Asked by At

I am learning ASP.Net MVC. I am referring Adam Freeman's Pro Asp.Net MVC 4 book. I came across a topic name Building Loosely Couple App in that Dependency Injection I was not getting what actually it is, so I tried to write his example in short cut.

I created an Interface IReservation as below

public interface IReservation
    {
        string getName();
    }

and a class that implements it as below

public class Reservation:IReservation
    {

        public string getName()
        {
            return "Wooww... It worked :D ";
        }
    }

Then I passed interface's object to my controller constructor same as in book. I have controller code as below

public class HomeController : Controller
    {
        IReservation res;
        public HomeController(IReservation reservation)
        {
            res = reservation;
        }
        public HomeController() { }
        public ActionResult Index()
        {
            string me = res.getName();
            return View();
        }
}

While debugging, I am getting NullReferenceException on line string me = res.getName();. I believe its because I am not creating it's instance using new keyword but I am not sure. Am I right here, if yes then how this example can be corrected? I have interface and implementing class in Models folder.

1

There are 1 answers

4
Darin Dimitrov On BEST ANSWER

You should remove the default constructor of your controller which is never injecting any IReservation instance:

public HomeController() { }

Now your controller definition becomes:

public class HomeController : Controller
{
    private readonly IReservation reservation;
    public HomeController(IReservation reservation)
    {
        this.reservation = reservation;
    }

    public ActionResult Index()
    {
        string me = this.reservation.getName();
        return View();
    }
}

All that's left now is to bootstrap and configure your favorite DI framework so that injects the proper instance of IReservation in your controller.

For example if you are using Ninject.MVC in your bootstrap:

kernel.Bind<IReservation>.To<Reservation>();

If you are using some other DI container you should obviously adapt the syntax to it and register the proper instance when bootstrapping your application.