My favorites | Sign in
Project Home Downloads Wiki Issues Source
Project Information
Members
Links

Repository with NHibernate

Introduction

This project serves as a working example on how to implement the Repository pattern in .NET using NHibernate (with FluentNHibernate). There is no official definition of the Repository pattern and many different implementations exist on the web. In my opinion, the purpose of this pattern is twofold: to abstract the underlying implementation of the DAL, and to provide a facade for NHibernate. I critically reviewed many implementations, grabbing little bits and pieces from each of them, and crafted what I feel is the best implementation. Enjoy.

Description

NHibernate (with FluentNHibernate) is a powerful object-relational mapper (ORM). However, being the good developers we are, we always make an attempt to decouple components of our systems where the opportunity arises, so that we will be able to easily replace NHibernate with the next great ORM. Enter the Repository pattern...

The beauty of Repository is in its simplicity. Grabbing an object from the database only requires two lines of code:

IRepository<Monkey> monkeyRepo = new NHibernateRepository<Monkey>();

Monkey m = monkeyRepo.Get(IdMonkey);

Programming against an interface (IRepository) is powerful because it decouples your system from the underlying implementation. The IRepository interface is incredibly simple, consisting of 5 methods:

public interface IRepository<T>
{
    T Get(object id);
    void Save(T value);
    void Update(T value);
    void Delete(T value);
    IList<T> GetAll();
}

As with any kind of abstraction, you lose some amount of control by limiting yourself to these 5 methods. As we should know, this isn't always a bad thing, otherwise we'd still be programming in assembly.

It goes without saying that you may require additional control over your data access layer - in this case, Repository may not be right for you. The most major drawback you should be concerned about is that lazy loading needs to be disabled. If this is a serious problem for you, check out the Unit of Work facade. This pattern is designed for small projects that deal with small amounts of data.

You may want to use this project as a starting point for your current project - go ahead. Just replace the domain classes with your own and away you go.

Powered by Google Project Hosting