The S#arp framework: The SharpArch.Web assembly – part II
Today we’ll keep looking at the SharpArch.Web assembly and we’ll take a quick look at the TransactionAttribute. TransactionAttribute is an ActionFilterAttribute which intercepts the ActionExecuting and ActionExecute exceptions for starting and ending a transaction. Here’s the code for that class:
public class TransactionAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
NHibernateSession.Current.BeginTransaction();
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
if (filterContext.Exception == null && NHibernateSession.Current.Transaction.IsActive) {
NHibernateSession.Current.Transaction.Commit();
}
}
}
As you can see, the code relies (yet again!) on the omnipresent NHibernateSession class we’ve met in a past post. Notice that the transaction is only committed when the action method doesn’t throw an exception and when the current transaction is still active. Combining this attribute with the WebSessionStorage we’ve met in the last post makes working with transactions (and db related stuff) from an action method a breeze…
If you don’t believe me, then take a look at the following action method (copied from the CustomersController class in the Northwind sample app):
[Transaction]
public ActionResult Create(string companyName, string assignedId) {
Customer customer = new Customer(companyName);
customer.SetAssignedIdTo(assignedId);
customerRepository.Save(customer);
return View(customer);
}
As you can see, there’s no evidence of database code here. This is probably good and it will let you isolate the action method code from any of those concerns. Simple and elegant.
And that’s it for today. Keep tuned for more on the S#arp framework.