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.