How I keep my repositories DRY and simple

A couple of weeks ago, my friend and colleague, Jonas, wrote an article about keeping your project and repositories DRY (Don’t Repeat Yourself). Instead of having a repository for each POCO object within your project, he created a IRepository. A repository each object could use to get the most used methods:

  • GetById()
  • GetAll()
  • Insert()
  • Delete()

These four functions is used in every repository 95% of the time. So I asked him; what about the times you would actually need a read-only repository? It’s not impossible you would want that.

So instead of having a “master” repository, I’d rather have a class for each object in my project. I would create an interface for each method to be reused:

public interface ICanGetAll<T>
{
    IEnumerable<T> GetAll();
}
 
public interface ICanGetById<TEntity, TKey>
{
    TEntity GetById(TKey id);
}
 
public interface ICanRemove<T>
{
    void Remove(T entity);
}
 
public interface ICanSave<T>
{
    void Save(T entity);
}

These interfaces gives us the freedom to implement them as you go. Yes, I still need a file with a repository class for each object. But that’s fine for me. Now I can make sure all my methods names are the same. Let’s say I have a Project object.

public interface IProjectRepository :
    ICanSave<Project>,
    ICanRemove<Project>,
    ICanGetById<Project, id>,
    ICanGetAll<Project>
{
    IEnumerable<Project> GetProjectsByCustomerId(int customerId);
}

This is not perfect in any way. Still, I don’t have to copy/paste a repository when I need a new one. I can simply select the methods required for the specific repository. That’s a bullet proof way for me!

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • FriendFeed
  • LinkedIn
  • MySpace

One Comment to “How I keep my repositories DRY and simple”

  1. Jonas Hovgaard 27 December 2009 at 5:38 pm #

    Hi Mark,

    Good to see that you are thinking out of the box. I never thought of that approach. This can really make the IRepository pattern totally flexible to whatever a specific object needs.

    I’m currently writing on my next post about IRepository. I hope you can improve that too :)


Leave a Reply