我可以同时使用每个网络请求的会话和 TransactionScope 吗?
您知道,为了在 Web 应用程序中实现每个 Web 请求的会话,我们经常在 Application_BeginRequest 中创建一个会话,并在 Application_EndRequest 全局事件处理程序中关闭它。然后每次访问数据库时,我们都通过 GetCurrentSession 获取当前会话,而不是通过 OpenSession 打开新会话。
那么是否有机会在 Web 应用程序中同时使用 session-per-web-request 和 TransactionScope 呢?根据NHibernate 3.0 Cookbook(第117页),它说对TransactionScope.Complete的调用应该在会话被释放之后发生。令人惊讶的是,尽管在同一章中讨论了 session-per-web-request 和使用 TransactionScope,但它没有提及这种情况。
using (var scope = new TransactionScope())
{
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
// do something here
}
scope.Complete();
}
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 session 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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您在每个请求中打开了多个会话/事务(可能是不同的数据库),这是使用 TransactionScope 的唯一充分理由。
如果是这种情况,只需在 Application_BeginRequest/Application_EndRequest 中创建并 Complete() 您的 TransactionScope,就像您为会话所做的那样。
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.