hspmadu
hspmadu

Reputation: 33

Repository pattern in MVC: controller code explanation

What is the purpose of SudentRepository in this example? Why do I need one?

public class StudentController : Controller
{
    private IStudentRepository _repository;

    public StudentController() : this(new StudentRepository())
    {

    }

    public StudentController(IStudentRepository repository)
    {
        _repository = repository;
    }

Upvotes: 0

Views: 45

Answers (1)

Charles
Charles

Reputation: 640

I updated to actually include a specific question that I think you're getting at. The purpose of StudentRepository is to encapsulate interactions with persisted data. The Controller need not know if its stored in a db, flat file, in memory, etc.

The reason you're injecting it in via an interface is because you may eventually have multiple implementations of that repository, and the interface is just a contract to ensure basic functionality across all implementations. This is called constructor injection (a type of dependency injection) in case you want to learn more.

Upvotes: 1

Related Questions