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?
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:
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With