Just sharing some of my inconsequential lunch conversations with you... RSS  

Tuesday, August 14, 2007

Transaction management: the last one please close the lights

When managing transactions on business layers we often cross upon the following pattern:

  • if the transaction was opened here, a commit will be issued;
  • if the transaction was opened by the caller, it's the caller responsibility to commit the data;

Now you know why I'm calling this post "the last one please close the lights".

Often this implementation is encapsulated on a method that know if the transaction was opened here. There's a tendency to name this method Commit, subverting the commit semantics.

So I've been calling it SetComplete - in memory of good old MTS. Yes, I know, SetComplete was a little widder (it enrolled transactions), but clearly better than Commit. Here's a sample:

void businessMethod1()
{
using (TransactionContext transactionContext = new TransactionContext())
{
businessMethod1();

transactionContext.SetComplete();
}
}

void businessMethod2()
{
using (TransactionContext transactionContext = new TransactionContext())
{
// do some stuff

transactionContext.SetComplete();
}
}

We can now safetly invoke businessMethod1 or businessMethod2 without worrying about transactions. And if we want to use them withing another transaction, we just have to honor the "all TransactionContext should be closed with a SetComplete()".

Have you notice no context was passed among business objects? This will be the subject of my next post.

No comments:

Development Catharsis :: Copyright 2006 Mário Romano