NHibernate 与 TransactionScope [英] NHibernate with TransactionScope

查看:18
本文介绍了NHibernate 与 TransactionScope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我一个关于在 NHibernate 中使用 TransactionScope 的快速概述?我需要对 session/IEnlistmentNotification/etc 做任何特别的事情吗?让这个工作?有什么陷阱需要我担心吗?例如,我可以替换我所有的休眠事务吗:

Can anyone give me a quick overview of using TransactionScope with NHibernate? Do I need to do anything special with the session/IEnlistmentNotification/etc. to get this to work? Are there any pitfalls that I should worry about? For example, can I replace all of my hibernate transactions:

var transaction = session.BeginTransaction();
try
{
    // code
    transaction.Commit();
}
catch (Exception)
{
    transaction.Rollback();
}

用这个?:

using (var scope = new TransactionScope())
{
    // code
    scope.Complete();
}

推荐答案

我已经使用 nHibernate 2.1 一段时间了,在经历了一些生产问题并尝试了很多变体之后,我们确定了以下方法,根据 避免泄漏与 NHibernate 和 TransactionScope 的连接:

I have been using nHibernate 2.1 for awhile, and after a few production issues and trying quite a few variations, we have settled on the following method, as per Avoiding Leaking Connections With NHibernate And TransactionScope:

        using (var scope = new TransactionScope(TransactionScopeOption.Required))
        {
            using (var session = sessionFactory.OpenSession())
            using (var transaction = session.BeginTransaction())
            {
                // do what you need to do with the session
                transaction.Commit();
            }
            scope.Complete();
        }

因为我们使用的是 MSMQ 和 WCF,所以我们不得不使用环境事务.

As we are using MSMQ and WCF so we had to use the ambient transaction.

我们发现不使用 session.BeginTransaction() 会导致连接泄漏.我们还发现在提交事务后重新使用会话会导致竞争条件(nHibernate 不是线程安全的,并且 DTSC 提交/回滚发生在后台线程上).

We found that not using session.BeginTransaction() caused a connection leak. We also found that re-using a session after committing a transaction caused a race condition (nHibernate is not thread safe and DTSC Commits/Rollbacks occur on a background thread).

这篇关于NHibernate 与 TransactionScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆