惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
Microsoft Azure Blog
Microsoft Azure Blog
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
小众软件
小众软件
F
Fortinet All Blogs
Microsoft Security Blog
Microsoft Security Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Hackread – Cybersecurity News, Data Breaches, AI and More
量子位
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
aimingoo的专栏
aimingoo的专栏
B
Blog RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
宝玉的分享
宝玉的分享
有赞技术团队
有赞技术团队
J
Java Code Geeks
WordPress大学
WordPress大学
The Cloudflare Blog

博客园 - hugh-lin

MySql数据库、表名大小写的问题 [转]Spring--简单使用quartz实现定时作业 [转]PowerDesigner使用技巧 IBatis的自动生成工具abator的改造 - hugh-lin - 博客园 Struts2.1开发笔记-2 Struts2.1开发笔记-1 PowerDesigner 12.5 导致 Word 2003鼠标没反应的解决方法 J2EE开发之常用开源项目介绍(转) [转]通过ScriptManager在客户端来调用服务器端方法或者webService的方法 - hugh-lin - 博客园 [转]关闭Visual Studio 实时调试器 [转]java安装配置 [转]文件缓存的方式减少网站负载 [转]C#中得到程序当前工作目录和执行目录的一些方法 [转] NHibernate对像版本控制使用示例 分页 oracle 导入/导出 [转]Datagridview 实现二维表头 [转]使用.NET实现断点续传 [转]IIS站点管理类 [转]C#的usb通讯编程
[转]Web项目下NHibernate的Session管理的解决方案
hugh-lin · 2007-11-07 · via 博客园 - hugh-lin


NHibernate的Session的管理一直是个问题,在系统开发中

如果有lazy="true",如果不对Session进行管理,会抛出以下错误:

CODE:

Failed to lazily initialize a collection - no session

在Web项目下的解决方案,就是在Application_BeginRequest方法中打开Session并放入HttpContext,在Application_EndRequest方法中关闭Sesssion就可以了。

还好,NHibernate1.2已经提供了相关的支持,如下:

在web.config中加入以下代码

CODE:

<httpModules>
        <add name="CurrentSessionModule" type="NHibernate.Example.Web.CurrentSessionModule" />
    </httpModules>

程序如下:

CODE:

using System;
using System.Web;
using NHibernate.Context;

namespace NHibernate.Example.Web
{
  public class CurrentSessionModule : IHttpModule
  {
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
        context.EndRequest += new EventHandler(Application_EndRequest);
    }

    public void Dispose()
    {
    }

    private void Application_BeginRequest(object sender, EventArgs e)
    {
        ManagedWebSessionContext.Bind(HttpContext.Current, ExampleApplication.SessionFactory.OpenSession());
    }

    private void Application_EndRequest(object sender, EventArgs e)
    {
        ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, ExampleApplication.SessionFactory);
  if(session !=null)
  {
        if (session.Transaction.IsActive)
        {
          session.Transaction.Rollback();
        }

        if (session != null)
        {
          session.Close();
        }
    }
    }
  }
}

posted on 2007-11-07 10:47  hugh-lin  阅读(782)  评论()    收藏  举报