NHibernate and Repository

Oct 17, 2010 at 12:59 PM
Edited Oct 17, 2010 at 1:02 PM

First off, I'm a newbie at NHibernate so please don't think I know best but...

I recently attended 'NHibernate Day' and one of the take-aways was, "do not wrap the NHibernate (NH) session in a repository". Assuming that the repository is used to try and abstract away the ORM used, the NH argument against this is that two ORMs will offer differing services. Therefore you either have to do an ODBC style DoHaveThisFunction test or only implement the lowest common set. I'm interested to hear your thoughts about it, again it's more about me understanding NH and this demo than it's a critisism of the implementation.

Coordinator
Oct 17, 2010 at 5:36 PM

Hi,

The reason why I'm still using the repository pattern has nothing to do with abstracting away NHibernate, but everything with the testability of the code that is relying on the repository. Suppose you need to write some specs that verify the behavior of some code that is doing data access through NH's ISession interface. In order for you to test this code in isolation, you may have to stub or mock (using a mocking framework such as Rhino Mocks or MOQ) the ISession. However, mocking a complex interface is always a bad practice because you end up with unreadable and hardly maintainable test code. That;s why I keep NH behind a very focused and specific interface that is easy to mock. And as a side effect of this very domain-specific interface, it is actually very easy to replace the actual implementation to switch from NH to EF4 or vice versa.

As a side note, also consider reading my latest post. It deals a bit with repositories as well. 

Oct 17, 2010 at 6:25 PM

Thanks for the reply, hmm restricting the interface for testing is an interesting angle. Just to play devils advocate, if you did remove the repository then wouldn't testing the 'client' be enough? So RecipeAggregate (or service, whatever)->RecipeRepository->NH would become RecipeAgg->NH and you'd mock/test IRecipeAgg rather than IRecipeRepository?

 

Coordinator
Oct 19, 2010 at 5:34 AM

It depends. In this particular case, the choice of using a repository or not is mostly dictated by the NCQRS framework I'm using for the CQRS/Event Sourcing part. However, a class that is handling both business logic AND database access is both violating the Single Responsibility Pattern and very difficult to test without unmaintainable test code. If you're practicing Test Driven Development you typically strive for code that complies to the SOLID principles. Those should help you create maintainable code.