If you take a look at this SO question I have a question on the next step.
Imagine you have two repositories generating Items and SubItems. I also have a UnitOfWork which acts as a context for changes to the (in this simple case) two different items.
There seem to be a few ways of generating a UnitOfWork, sometimes this is injected into the repository, sometimes this can be generated by a factory (and then either injected or retrieved from the factory.
My question is how does the UnitOfWork notify the repositories that its changes are now to be committed?
I guess I can have the repository subscribe to events on the UnitOfWork for commit/rollback.
Second question, the idea of the unit of work is, if I have this right, to co-ordinate updates that may conflict. Using my example of Item and SubItem (an Item has a number of SubItems) the UnitOfWork coordinates this so the Item is written first allowing the SubItem to be written? Now I seem to need the unit of work to know about the repositories which seems wrong.
Thanks.
The way I structured my repository was to have the UnitOfWork simply be a “token”, spawned by a BeginUnitOfWork() method on the Repo, that then had to be passed to pretty much any other method on the Repo that made DB calls. The only thing it has to know how to do, conceptually, is be disposed, which when that happens causes the NHibernate session associated with that UOW to be closed. It does this by being given a delegate to a protected method in the Repo that it then called back in its Dispose method. What this does for me is completely abstract the actual data-access mechanism; I can implement the same pattern regardless of the back end, and users of the pattern cannot hack the UnitOfWork to get at the actual data-access mechanism.
YMMV; it does require classes that need to perform DB objects to be dependent on the repository as well as the unit of work. You could use additional delegates to expose methods on the UnitOfWork itself that would allow it to be the only dependency.