Repository and Unit Of Work

Wednesday, October 01, 2014

I was looking for some help on Entity Framework and I ran across Rob Conery's blog post contending that Repositories don't work with Unit Of Work. I believe his strongest point is his first, that you can't decouple the Repository from the Entity Framework context. He points to a single implementation and copies that code to 'Prove' this point. The code looks something like this:

public class StudentRepository : IStudentRepository, IDisposable
{
   private SchoolContext context;
   .
   .
   .
}

Rob then points to the 'private SchoolContext' line as proof that this is tightly coupled to Entity Framework. Hmm....

The most reasonable implementations that I have seen take this a stop further and create an IContext to decouple the SchoolContext. That way you can test without having a database. That's what I do. When I test, I want to be able to test as much of the real code as I can without worrying about the state of the database. I spent a fair amount of time reading implementations of the Repository and Unit Of Work patterns trying to figure what worked and what didn't. What makes the most sense to me is using it decouple Entity Framework and the database to allow me to test. I really like having the ability to test my code without a database. This is especially true on projects with large, unwieldy databases. Resetting a huge database for every test run is a pain.

For a while, as I plowed through a bunch of code trying to understand the purpose of the Repository pattern, I shared Rob's believe, but then I had my aha moment. So, am I missing something here or is Rob?

Comments