I'd like to write a simple unit of work class that would behave like this:
using (var unitOfWork = new UnitOfWork())
{
// Call the data access module and don't worry about transactions.
// Let the Unit of Work open a session, begin a transaction and then commit it.
}
This is what I have so far (any comments will be welcome if you think my design is wrong):
class UnitOfWork : IDisposable
{
ISession _session;
ITransation _transaction;
.
.
.
void Dispose()
{
_transaction.Commit();
_session.Dispose();
}
}
What I would like to do is to roll back the transaction in case the data acess code threw some exception. So the Dispose()
method would look something like:
void Dispose()
{
if (Dispose was called because an exception was thrown)
{
_transaction.Commit();
}
else
{
_transaction.RollBack();
}
_session.Dispose();
}
Does it make sense? And if so, how can it be done?
After all, I implemented a method through which all operations should be performed:
class UnitOfWork : IDisposable
{
...
public void DoInTransaction(Action<ISession> method)
{
Open session, begin transaction, call method, and then commit. Roll back if there was an exception.
}
}