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.

2 Answers
2

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

I think yes and no. The NHibernate session itself is soem kind of generic repository. So adding a additional repository is in general nothing more than adding a facade to the session object.
–
Jan SelkeSep 6 '11 at 9:13

in fact my answer begin like "The repository pattern is not required..." it can be just an architectural decision make against the business needs that's it
–
Massimiliano PelusoSep 6 '11 at 9:15

I totally agree on that. But I was missing the point that session itself is a repository, that's all.
–
Jan SelkeSep 6 '11 at 9:20

Advantage of using repository pattern is to mock your data access layer, so that you can test your business layer code without calling DAL code. There are other big advantages but this seems to be very vital to me.

+1 the ActiveRecord pattern makes it very difficult to isolate the DAL for mocking, usually ending up with the unit tests requiring their own database (in which case the unit test becomes an integration test).
–
MattDaveySep 26 '11 at 8:57