I am trying to get TransactionScope and nhibernate Stateless Sessions playing together nicely,

My unit of work class looks like this at a high level

using(var scope = new TransactionScope())
{
    using (var transaction = session.BeginTransaction())
    {
        session.SaveOrUpdate(entity);
        transaction.Commit();
    }
    scope.Complete();
}

Source

The problem I am getting is an intermittent TransactionAbortedException when the TransactionScope disposes after a commit/complete

The wierd thing is the inner exception looks to be caused by nHibernate trying to execute a SQL command during the dispose and triggering the error due to complete already being called:

   at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
   at NHibernate.AdoNet.AbstractBatcher.ExecuteBatchWithTiming(IDbCommand ps)
   at NHibernate.AdoNet.AbstractBatcher.ExecuteBatch()
   at NHibernate.Engine.ActionQueue.ExecuteActions()
   at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
   at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
   at NHibernate.Impl.SessionImpl.Flush()
   at NHibernate.Transaction.AdoNetWithDistributedTransactionFactory.DistributedTransactionContext.System.Transactions.IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment)

I have tried manually flushing my stateless session before complete using:

session.GetSessionImplementation().Flush()

Doesn't seem to help.

Any ideas how to stop this happening?

有帮助吗?

解决方案

Eventually figured out that this line in the stack trace:

NHibernate.Impl.SessionImpl.Flush()

Was indicating that there was a standard Session (not stateless) with pending changes in this transaction that needed to be flushed, still not sure why it waited till after the dispose to flush them. Either way, I fixed this by flushing the standard session as well as the stateless one before disposing the unit of work

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top