Wednesday, December 31, 2008

ATM with NHibernate

It is cool what you can achieve using anonymous methods and lambdas. Usually to persist an entity to datastore, you would do something like this with NHiberante:

public void SaveOrder()
{
using (var session = IoC.Resolve<ISessionFactory>().OpenSession())
{
var transaction = session.BeginTransaction();

try
{
var o = new Order
{
ProductName = "Ice Creams",
Description = "Lots of strawberry ice creams"
};

session.Save(o);
session.Flush();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}

but now you can abstract away the whole transaction creation and commit / rollback thing. Transactions will be rolledback automagically in case an exception occurs :

public void SaveOrder()
{
With.Transaction(() =>
{
var o = new Order
{
ProductName = "Ice Creams",
Description = "Lots of ice strawberry creams"
};

UnitOfWork.CurrentSession.Save(o);
});
}
hmmmmm…how is that possible? all the magic is in the With class and UnitOfWork implementation which are available with lots of other stull in Rhino Tools as free as it can be. In brief here’s how it works :
public static class Using
{
public static void Transaction(Action action)
{
using (UnitOfWork.Start())
using (var tx = UnitOfWork.Current.BeginTransaction())
{
try
{
action.Invoke();
tx.Commit();
}
catch
{
tx.Rollback();
throw;
}
}
}
}
You should note that this stuff will still work with pre .NET 3.5 via anonymous methods. This one was a real eye-opener! This provides centeral exception handling, automatic transaction management, etc. which will lead to much cleaner design. What else do you need?! Ideas?
Submit this story to DotNetKicks Shout it

No comments: