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.
You should remove the default constructor of your controller which is never injecting any
IReservation
instance:Now your controller definition becomes:
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: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.