Tuesday, July 6, 2010

overcomplicating things with the repository pattern

The Repository pattern was used in a project by some team members 6 or so months ago and it's being mentioned again along with concepts of an Aggregate Root in discussions on refactoring another project.  Both of these projects were C# projects using LINQ to SQL.   While working on the first project I kept thinking that the repository pattern seemed to just over complicate things and I couldn't see what real benefit it brought to a fairly simple application.  Now, I've done some further reading on Aggregate Roots and found ties to the repository pattern again.  As I read through several definitions I kept thinking that the main benefits are already provided via LINQ and implementing it on top seemed to only add another abstraction layer.  I did some more searching on the subject and found this article: Repository is the new Singleton and it just echoed everything I was thinking.

Creating a repository for data that is already in your DB is overkill when you are using LINQ (and likely any modern ORM) for accessing that data since the data access provided by LINQ is itself making use of the repository pattern .  A good place where the repository pattern would be useful is where you may have different sources of data.

Here is another interesting article about the Purpose of the Repository Pattern that talks about some of the issues when using this pattern along with LINQ.  The DataContext issues he mentions exist generally in a Web Application built on LINQ and not just when using repositories.  Our team got around some of the DataContext issues by using a DataContext Factory that we found that creates a scoped DataContext within the HttpContext and while within the scope of the HttpContext it always returns the same DataContext.  This helps keep anything within the HttpRequest in the same Unit of Work.  It was also written to work within the current thread if a HttpRequest is not available (a non-web app).

1 comment:

  1. One thing I didn't consider when I first posted this was how using the Repository Pattern makes the system easier to unit test by using mocks or fakes.

    ReplyDelete