【问题标题】:StructureMap/NHibernate Session Per Request including constant transcation每个请求的 StructureMap/NHibernate 会话,包括常量事务
【发布时间】:2009-11-29 20:59:19
【问题描述】:

我刚开始在我的 MVC 应用程序中使用 StructureMap,一切都很好,除了以正确的方式处理我的 ITranscation

我想做的是在每个请求上创建一个新的 ISession。与此一起,我想开始交易。

在请求结束时,我将提交交易。

我的问题是,如何使用 StructureMap 以最佳方式做到这一点。我在 Google 上找到了很多示例,但没有一个会根据请求启动事务,我真的不想在我的方法中这样做。

提前致谢!

【问题讨论】:

    标签: asp.net-mvc nhibernate structuremap


    【解决方案1】:

    【讨论】:

    【解决方案2】:

    这可能不是那么容易,但这是我的看法。创建一个基本上包装会话和事务的工作单元,并将其存储起来以供请求使用,并在请求结束时提交或回滚。

    public interface IUnitOfWork : IDisposable
    {
        ISession Session { get; }
        void Commit();
        void Rollback();
    }
    

    实现可能如下所示:

    public class UnitOfWork : IUnitOfWork
    {
        private readonly ITransaction _tx;
        public ISessionFactory SessionFactory { get; set; }
    
        public UnitOfWork()
        {
            SessionFactory = ObjectFactory.GetNamedInstance<ISessionFactory>(Keys.SessionFactoryName);
            Session = SessionFactory.OpenSession();
            _tx = Session.BeginTransaction();
        }
    
        public UnitOfWork(ISessionFactory sessionFactory)
        {
            SessionFactory = sessionFactory;
            Session = SessionFactory.OpenSession();
            _tx = Session.BeginTransaction();
        }
    
        public ISession Session { get; private set; }
    
        public void Commit()
        {
            if (_tx.IsActive)
                _tx.Commit();
        }
    
        public void Rollback()
        {
            _tx.Rollback();
        }
    }
    

    只需在 endrequest 处处理工作单元。

    【讨论】:

    • 这正是我所需要的,谢谢!然后我应该调用 Commit() 并在我的 IHttpModule 中处理 EndRequest 吗?
    • 是的,不要尝试在提交后处理事务(它会在提交后处理)。只是工作单元。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 2011-11-09
    • 2012-10-23
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多