asp.net mvc3 nhibernate 声明式事务

日常开发中,经常使用NHibernate事务。

因为NHibernate不支持嵌套式事务操作,所以ASP.NET MVC中通常使用一个事务来封装一次请求中的数据库操作。

下面是我认为比较漂亮的写法。

using System.Web.Mvc;
using NHibernate;

namespace WebMVC.Filters
{
    public class Transactional : ActionFilterAttribute
    {
        protected ISession _Session;

        public Transactional()
        {
            _Session = DependencyResolver.Current.GetService<ISession>();
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _Session.BeginTransaction();
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (_Session == null || !_Session.Transaction.IsActive)
                return;

            if (filterContext.Exception != null)
                _Session.Transaction.Rollback();
            else
                _Session.Transaction.Commit();
        }
    }
}

使用起来很方便。

using System.Web.Mvc;
using WebMVC.Filters;

namespace WebMVC.Controllers
{
    public class CustomersController : Controller
    {
        protected ICustomersRepository _CustomersRepository;

        public CustomersController(ICustomersRepository customersRepository)
        {
            _CustomersRepository = customersRepository;
        }

        [Transactional]
        public ActionResult List()
        {
            return View(_CustomersRepository.FindAll());
        }
    }
}
posted @ 2011-05-14 02:12  Kenneth Byron  阅读(2337)  评论(3编辑  收藏  举报