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 阅读(1628) 评论(3) 编辑 收藏

 回复 引用 查看   
#1楼 2011-05-14 11:44 Dickhead      
在controll开启事务这样做好吗?感觉应该在业务层开启
 回复 引用 查看   
#2楼 2011-05-14 11:53 Gray Zhang      
直接把Action当作业务层,个人还是比较欣赏这种轻便的设计的
 回复 引用 查看   
#3楼 2011-05-14 14:48 Genius Zhang      
引用Dickhead:在controll开启事务这样做好吗?感觉应该在业务层开启

比较赞同这个,因为我们的Action未必每个都要进行事务。。。在业务层做会比较好一些,如果使用了NH,我觉得还可以使用一下Spring.NET,做业务层的AOP事务。。。