开发者

Can I use both session-per-web-request and TransactionScope?

开发者 https://www.devze.com 2023-04-05 21:31 出处:网络
You know, to implement session-per-web-request in a web application we often create a session in Application_BeginRequest and close it in Application_EndRequest global event handlers. And then every t

You know, to implement session-per-web-request in a web application we often create a session in Application_BeginRequest and close it in Application_EndRequest global event handlers. And then every time we access to database, we get the current session by GetCurrentSession instead of open a new s开发者_如何学JAVAession by OpenSession.

So is there any chance to use both session-per-web-request and TransactionScope in a web application? According to NHibernate 3.0 Cookbook (page 117), it says that the call to TransactionScope.Complete should occur after the session has been disposed. Surprisingly it does not say any word about this situation although both session-per-web-request and using TransactionScope are discussed in the same chapter.

using (var scope = new TransactionScope())
{
  using (var session = sessionFactory.OpenSession())
  using (var tx = session.BeginTransaction())
  {
     // do something here
  }

  scope.Complete();
}


I'm going to assume you have more than one session/transaction open in each request (probably different databases), which is the only good reason to use a TransactionScope.

If that's the case, just create and Complete() your TransactionScope in Application_BeginRequest/Application_EndRequest, just like you are doing for the Session.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号