R – NHibernate Passing Session to the Repository

nhibernate

How would I go about passing a session to a repository class?

Let's say that the I have two projects.

1) TestSuite
2) BusinessObjects

The repository is contained in the BusinessObjects project. The NHibernate session is opened in the TestSuite project. Now, I want to use the same session since the TestSuite project starts a transaction on that session. Currently, I am using the following:

var repository = new CustomerRepository(_session);

Of course, this looks ugly! I am thinking somehow a dependency injection framework can be hooked and provide me with the ISession object without having to pass into the repository.

Best Answer

In our WCF Service we actually use a UnitOfWork which wraps a single operation and stores the ISession for that operation.

The repositories know how to get an ISession from the current unit of work they are running under.

In terms of testing we have a base test class that any test class which contains tests that touch the database inherits from. We then control the starting and ending of a unit of work in the testfixturesetup. Has worked fairly well for us once you get use to the fact that in the version of NUnit we use teardown is NOT guaranteed to run (in case of an unhandled exception during setup or the test).

Related Topic