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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 rolled back automagically in case an exception occurs:

1
2
3
4
5
6
7
8
9
10
11
12
13
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 short here’s how it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static class With
{
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 central exception handling, automatic transaction management, etc. which will lead to much cleaner design.