A data persistence abstraction
The Repository Pattern has gained quite a bit of popularity since it was
first introduced as a part of Domain-Driven
Design in 2004.
Essentially, it provides an abstraction of data, so that your application
can work with a simple abstraction that has an interface approximating that of
a collection.
Adding, removing, updating, and selecting items from this collection is
done through a series of straightforward methods, without the need to deal with
database concerns like connections, commands, cursors, or readers.
Although the pattern is very popular, it is also frequently
misunderstood and misused.
There are many different ways to implement the Repository pattern. Let’s
consider a few of them.
Repository Per Entity or
Business Object
The simplest approach, especially with an existing system, is to create
a new Repository implementation for each business object you need to store or
to retrieve from your persistence layer.
Further, you should only implement the specific methods you are calling
in your application.
Avoid the trap of creating a “standard” repository class, base class, or
default interface that you must implement for all repositories.
Yes, if you need to have an Update or a Delete method, you should strive
to make its interface consistent, but don’t implement a Delete method on your
LookupTableRepository that you’re only ever going to be calling List() on.
The biggest benefit of this approach is YAGNI – you won’t waste any time implementing methods
that never get called.
Generic Repository Interface
Another approach is to go ahead and create a simple, generic interface
for your Repository.
You can constrain what kind of types it works with to be of a certain
type, or to implement a certain interface
which is we are going to see today.
The advantage of this approach is that it ensures you have a common
interface for working with any of your objects.
You can also simplify the implementation by using a Generic Repository
Implementation.
Generic Repository
Implementation
Assuming you create a Generic Repository Interface, you can implement
the interface generically as well.
Once this is done, you can easily create repositories for any given type
without having to write any new code, and your classes the declare dependencies
can simply specify IRepository<Item> as the type, and it’s easy for your
IoC container to match that up with a Repository<Item> implementation.
You can see an example Generic Repository Implementation, using Entity
Framework, here.
No comments:
Post a Comment