C# – Why is the Repository pattern needed in NHibernate

cnetnhibernate

I am reading the official Your first NHibernate based application.

While the tutorial is good and easy to follow, I am wondering why the Repository pattern is used.

In the various Add, Update, Remove methods in the ProductRepository implementation, the code is nearly identical – they are all using transactions, and the difference is in the "meat" i.e. call session.Save int the Add method, session.Delete in the remove method.
(The page lacks HTML anchors, but you can search the page for the relevant code like public void Remove, public void Add)

That code just "feels wrong".

Why is the author using the Repository pattern – is it just for demonstration of using NHibernate or is that required or some other reason?

Ps. My background is from Ruby on Rails using ActiveRecord so I'm trying to make sense of how NHibernate works/is used.

Best Answer

The repository pattern is not required. As for all the other pattern is an "Architectural" decision that you have to make against your business needs. In general the repository Pattern is used to implement the "Entity Persistance Ingorance" that means that your entities don’t know anything on how to persist themselves on your storing device (Database,XML,TextFile,etc). If for example you have an entity Address it won’t contains the persistence logic (you won’t find anywhere something like address.Save or address.Update) but you will pass your entity to a repository method which is in charge to persist the changes

Related Topic