NHibernate与TransactionScope [英] NHibernate with TransactionScope
问题描述
任何人都可以给我快速概述如何将TransactionScope与NHibernate一起使用吗?我需要对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,在遇到了一些生产问题并尝试了许多变体之后,我们根据以下方法确定了以下方法: a href ="http://davybrion.com/blog/2010/05/avoiding-leaking-connections-with-nhibernate-and-transactionscope/">避免与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屋!