Im new in C#,i have read about constructor,and i have learned the reason we use them is we can assign whatever we want at the time of construct,but something which is difficult for me to understand is,i have a IRepository student like:
public interface IStudentRepository
{
object getAll();
}
i implemented it in StudentRepository:
public class StudentRepository:IStudentRepository
{
public testDBEntities DB = new testDBEntities();
public object getAll()
{
var reslt = (from s in DB.Students
select new StudentViewModel
{
Name = s.Name,
Id=s.Id
});
return reslt;
}
}
in my homeController i can do like the following:
IStudentRepository _repository=new StudentRepository();
public JsonResult Index()
{
var m= _repository.getAll();
return Json(m,JsonRequestBehavior.AllowGet);
}
why should i have a constructor then?like:
IStudentRepository _repository=new StudentRepository();
public HomeController(StudentRepository _repository)
{
this._repository = _repository;
}
public JsonResult Index()
{
var m= _repository.getAll();
return Json(m,JsonRequestBehavior.AllowGet);
}
im sorry if my question is basic but i could not find a right answer,thanks in advance
IStudentRepository
. Constructor injection is one method (probably the most common) of dependency injection.