Sergey Shishkin

on agile software development

Repository Pattern Revised

(see also specification, unit of work)

It Should Not Be That Complex

Last week I was implementing NHibernate-based data access infrastructure. While looking for existing implementations I saw a lot of code, where NHibernate leaks into the domain layer either in the form of queries (HQL or Criteria API) or a Unit of Work. Although some of the implementations succeed in decoupling the infrastructure and the domain layers, still these implementations are much too complex to maintain. For example, if you abstract complex queries with Specifications, you still have specification implementations coupled to NHibernate. Also manipulating pure ISession objects in the application layer is commonly considered to be OK.

This post series provides a much simpler look at the implementation of the good old repository (this post), specification and unit of work patterns.

Linq To Rescue

Though we have some issues with Linq to SQL, the Linq itself allows us to get rid of HQL and Criteria in our domain layer. Thanks to Linq to NHibernate (Linq2NH) we can now abstract NHibernate queries with the nice Linq syntax. Meet the simplest ever repository interface:

public interface IRepository<T>


    void Save(T entity);

    void Delete(T entity);

    T Get(object key);

    IQueryable<T> AllEntities();


Now we can write client code like this:

var customers =

    from customer in repository.AllEntities()

    where customer.FirstName.StartsWith(name) ||


    select customer;

Queries are now expressed in Linq and are not coupled to the infrastructure. Great! But now queries are all around. Let’s encapsulate them.



Written by Sergey Shishkin

17.08.2008 at 16:32

Posted in Data Access

%d bloggers like this: