P&P: Repository and Specification Patterns
I’ve been using the Repository pattern but I’ve struggling with it a bit. Surfing the web returns good samples, the problem is that, after reading many posts about it, I came to the conclusion that there are two kinds of implementations.
First Approach: The Specific Repository
The specific repository implementation takes us to have a interface for each entity that defines all of the data access methods that we need to perform.
So, if we want to access data from a Customer, we would build first a ICustomerRepository and and LinqCustomerRepository that would implement our interface:

Has you can see, we have a method for each action we want to perform. While this implementation serves the repository purpose, to me it feels more like a Service layer .
Second Approach: The Generic Repository
This approach uses a generic interface and implementation for the common actions:

This approach, to me, reflects more the repository pattern in the current available technology allowing us to have simplicity in our repositories thru the use of generics.
With this approach we also might use the Specification pattern for querying the data container.
The Specification Pattern
With this pattern we can encapsulate our queries. To perform this task we must first create a abstract class that will serve as base for all our queries:

With this we can now, for instance, create a query to get all customers by gender:

To use it in our Service Layer we just need to:

Our Find method of the Repository will get all:

Tagged as P&P, Patterns, Repository, Specification + Categorized as Development




