I'm thinking about making my own IUnitOfWork
implementation for an NHibernate persistence layer.
It seems that the right way to do this would be to have the ISession
and the ITransaction
instantiated in the constructor, and then disposed in the destructor or the Dispose()
method.
Of course, if someone invokes the Save()
method, then the ISession
would be flushed and the ITransaction
would be complete, so after calling Save()
, there would not be a valid open transaction to Save()
again... unless I committed the first transaction and immediately opened another, new transaction. But is this a good idea?
Design-wise, it makes sense to do one commit operation, but I will not necessarily have control of the code and other developers may be less disciplined about following the UnitOfWork pattern.
Do I lose/ gain anything by trying to make the UnitOfWork tolerant to multiple transactions per session? Should I just check for an open transaction and throw an exception if it's already been committed, rather than making a new transaction?
To answer the first question: yes it is possible to have multiple transactions in one session.
Is is a good idea? It depends.
The problem is that changing data in the first transaction would be committed, while it is not sure if the whole unit of work (session) gets committed at the end. When you get, let's say, a StaleObjectException in a later transaction, you already had some data committed. Note that this kind of exception makes your session unusable and you had to destroy it anyway. Then it is hard to start over and try again.
I would say, it works well under these circumstances:
UI Application
Errors are handled by the user interactively. This means that the user can see what's actually stored in a case of error and repeats the changes he made.
Changes are only flushed in the last transaction
The session as implemented by NH only flushes changes at the end or "when necessary". So it would be possible to keep changes in memory until the session gets committed. The problem is that NH needs to flush the session before every query, which is hard to control. It can be turned off, which leads to side effects. When writing simple transactions, you may have it under control. In a complex system it's virtually impossible to make sure that nothing is going wrong.
The Simple Way (tm)
I wrote the persistence layer of a quite large client-server system. In such a system, you don't have a user handling errors directly. You need to handle the errors in the system and return control to the client in a consistent state.
I simplified the whole transaction handling to an absolute minimum, in order to make it stable and "idiot proof". I have always a session and a transaction created together and it gets either committed or not.