日常开发中,经常使用NHibernate事务。
因为NHibernate不支持嵌套式事务操作,所以asp.net MVC中通常使用一个事务来封装一次请求中的数据库操作。
下面是我认为比较漂亮的写法。
view sourcePRint?01 using System.Web.Mvc;
02 using NHibernate;
03
04 namespace WebMVC.Filters
05 {
06 public class Transactional : ActionFilterAttribute
07 {
08 protected Isession _Session;
09
10 public Transactional()
11 {
12 _Session = DependencyResolver.Current.GetService<ISession>();
13 }
14
15 public override void OnActionExecuting(ActionExecutingContext filterContext)
16 {
17 _Session.BeginTransaction();
18 }
19
20 public override void OnActionExecuted(ActionExecutedContext filterContext)
21 {
22 if (_Session == null || !_Session.Transaction.IsActive)
23 return;
24
25 if (filterContext.Exception != null)
26 _Session.Transaction.Rollback();
27 else
28 _Session.Transaction.Commit();
29 }
30 }
31 }
使用起来很方便。
view sourceprint?01 using System.Web.Mvc;
02 using WebMVC.Filters;
03
04 namespace WebMVC.Controllers
05 {
06 public class CustomersController : Controller
07 {
08 protected ICustomersRepository _CustomersRepository;
09
10 public CustomersController(ICustomersRepository customersRepository)
11 {
12 _CustomersRepository = customersRepository;
13 }
14
15 [Transactional]
16 public ActionResult List()
17 {
18 return View(_CustomersRepository.FindAll());
19 }
20 }
21 }
-
|