Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an interface used when implementing the repository pattern, with entity framework?

When implementing the repository pattern, in conjunction with entity framework, why do I see many examples using an interface for their repository class? A specific example of a reference of this is here.

What's the point of the interface? Why not just the class? Will there really need to be more than one class subscribing to that very specific interface, for just Employees, for example?

like image 933
Ryan Avatar asked Mar 22 '23 01:03

Ryan


1 Answers

It's a frequently used pattern, quite often used specifically for unit testing, not really specific to entity framework, or repository pattern, or even any data access kind. Another great benefit is that it gives the chance to latter provide an alternate implementation without change the code using it. Consider for example this code, that uses the dependency injection pattern:

public class EmployeeService
{
    private readonly IEmployeeRepository employeeRepository;

    public EmployeeService(IEmployeeRepository employeeRepository)
    {
        this.employeeRepository=employeeRepository;
    }

    public IEnumerable<Employee> GetAllEmployees()
    {
        IEnumerable<Employee> employeeList=this.employeeRepository.GetAll();
        //Optionally do some processing here
        return employeeList;
    }
}

By having the interface in the repository, note that you now can work entirely using the interface, without ever mentioning the actual repository, this is the real value of it. It gives mainly two benefits:

  • If you want to write an automated unit test for this class, you may give it a fake implementation of the IEmployeeRepository, which would not go to the real database, but instead return a hardcoded list, so that you can test your method without worrying about the DB for now. This is called a 'Mock', and is often the main reason of putting that interface there. There are also a couple of libraries that automate that process, all relying on the fact that they generate a fake class implementing an interface. By far, that's the most common reason for putting an interface like that.
  • You may decide sometime in the future that you want to replace entity framework with something else, or, say, want to implement a repository to something different than a relational DB. In this case, you would write another repository, implementing the very same interface, but doing something completely different. Given that the services using it rely only on the interface that code will work entirely unmodified as long as the same contract is respected (of course, the code that actually creates the repo and gives it to the service must change, but that's another history). That way the same service works the same no matter where it reads/saves the data.
like image 65
Alejandro Avatar answered Apr 07 '23 15:04

Alejandro