Web项目下NHibernate的Session管理的解决方案 【转】
2009-06-10 08:57
253 查看
NHibernate的Session的管理一直是个问题,在系统开发中
如果有lazy="true",如果不对Session进行管理,会抛出以下错误:
CODE:
Failed to lazily initialize a collection - no session
[Copy to clipboard]
在Web项目下的解决方案,就是在Application_BeginRequest方法中打开Session并放入HttpContext,在Application_EndRequest方法中关闭Sesssion就可以了。
还好,NHibernate1.2已经提供了相关的支持,如下:
在web.config中加入以下代码
CODE:
<httpModules>
<add name="CurrentSessionModule" type="NHibernate.Example.Web.CurrentSessionModule" />
</httpModules>
[Copy to clipboard]
程序如下:
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();
}
}
}
}
}
====================================================================
另外我在Codesmith中也找到了一个关于session管理的模版,请看代码
using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace NHibernate.Generated.Base
{
public interface INHibernateSessionManager : IDisposable
{
// Methods
INHibernateSession CreateSession();
ISession CreateISession();
// Properties
INHibernateSession Session { get; }
}
/// <summary>
/// A Singleton that creates and persits a single SessionFactory for the to program to access globally.
/// This uses the .Net CallContext to store a session for each thread.
///
/// This is heavely based on 'NHibernate Best Practices with ASP.NET' By Billy McCafferty.
/// http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx
/// </summary>
public class NHibernateSessionManager : INHibernateSessionManager
{
#region Static Content
private static INHibernateSessionManager _nHibernateSessionManager = null;
/// <summary>
/// Set method is exposed so that the INHibernateSessionManager can be swapped out for Unit Testing.
/// NOTE: Cannot set Instance after it has been initialized, and calling Get will automatically intialize the Instance.
/// </summary>
public static INHibernateSessionManager Instance
{
get
{
if(_nHibernateSessionManager == null)
_nHibernateSessionManager = new NHibernateSessionManager();
return _nHibernateSessionManager;
}
set
{
if (_nHibernateSessionManager != null)
throw new Exception("Cannot set Instance after it has been initialized.");
_nHibernateSessionManager = value;
}
}
#endregion
#region Declarations
private ISessionFactory _sessionFactory = null;
private const string _sessionContextKey = "NHibernateSession-ContextKey";
#endregion
#region Constructors & Finalizers
/// <summary>
/// This will load the NHibernate settings from the App.config.
/// Note: This can/should be expanded to support multiple databases.
/// </summary>
private NHibernateSessionManager()
{
_sessionFactory = new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory();
}
~NHibernateSessionManager()
{
Dispose(true);
}
#endregion
#region IDisposable
private bool _isDisposed = false;
public void Dispose()
{
Dispose(false);
}
private void Dispose(bool finalizing)
{
if (!_isDisposed)
{
// Close SessionFactory
_sessionFactory.Close();
_sessionFactory.Dispose();
// Flag as disposed.
_isDisposed = true;
if (!finalizing)
GC.SuppressFinalize(this);
}
}
#endregion
#region Methods
public INHibernateSession CreateSession()
{
return new NHibernateSession(CreateISession());
}
public ISession CreateISession()
{
ISession iSession;
lock (_sessionFactory)
{
iSession = _sessionFactory.OpenSession();
}
return iSession;
}
#endregion
#region Properties
public INHibernateSession Session
{
get
{
INHibernateSession session = ContextSession;
// If the thread does not yet have a session, create one.
if (session == null)
{
session = CreateSession();
// Save to CallContext.
ContextSession = session;
}
return session;
}
}
private INHibernateSession ContextSession
{
get
{
if (IsWebContext)
return (NHibernateSession)System.Web.HttpContext.Current.Items[_sessionContextKey];
else
return (NHibernateSession)System.Runtime.Remoting.Messaging.CallContext.GetData(_sessionContextKey);
}
set
{
if (IsWebContext)
System.Web.HttpContext.Current.Items[_sessionContextKey] = value;
else
System.Runtime.Remoting.Messaging.CallContext.SetData(_sessionContextKey, value);
}
}
private bool IsWebContext
{
get { return (System.Web.HttpContext.Current != null); }
}
#endregion
}
}
如果有lazy="true",如果不对Session进行管理,会抛出以下错误:
CODE:
Failed to lazily initialize a collection - no session
[Copy to clipboard]
在Web项目下的解决方案,就是在Application_BeginRequest方法中打开Session并放入HttpContext,在Application_EndRequest方法中关闭Sesssion就可以了。
还好,NHibernate1.2已经提供了相关的支持,如下:
在web.config中加入以下代码
CODE:
<httpModules>
<add name="CurrentSessionModule" type="NHibernate.Example.Web.CurrentSessionModule" />
</httpModules>
[Copy to clipboard]
程序如下:
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();
}
}
}
}
}
====================================================================
另外我在Codesmith中也找到了一个关于session管理的模版,请看代码
using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace NHibernate.Generated.Base
{
public interface INHibernateSessionManager : IDisposable
{
// Methods
INHibernateSession CreateSession();
ISession CreateISession();
// Properties
INHibernateSession Session { get; }
}
/// <summary>
/// A Singleton that creates and persits a single SessionFactory for the to program to access globally.
/// This uses the .Net CallContext to store a session for each thread.
///
/// This is heavely based on 'NHibernate Best Practices with ASP.NET' By Billy McCafferty.
/// http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx
/// </summary>
public class NHibernateSessionManager : INHibernateSessionManager
{
#region Static Content
private static INHibernateSessionManager _nHibernateSessionManager = null;
/// <summary>
/// Set method is exposed so that the INHibernateSessionManager can be swapped out for Unit Testing.
/// NOTE: Cannot set Instance after it has been initialized, and calling Get will automatically intialize the Instance.
/// </summary>
public static INHibernateSessionManager Instance
{
get
{
if(_nHibernateSessionManager == null)
_nHibernateSessionManager = new NHibernateSessionManager();
return _nHibernateSessionManager;
}
set
{
if (_nHibernateSessionManager != null)
throw new Exception("Cannot set Instance after it has been initialized.");
_nHibernateSessionManager = value;
}
}
#endregion
#region Declarations
private ISessionFactory _sessionFactory = null;
private const string _sessionContextKey = "NHibernateSession-ContextKey";
#endregion
#region Constructors & Finalizers
/// <summary>
/// This will load the NHibernate settings from the App.config.
/// Note: This can/should be expanded to support multiple databases.
/// </summary>
private NHibernateSessionManager()
{
_sessionFactory = new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory();
}
~NHibernateSessionManager()
{
Dispose(true);
}
#endregion
#region IDisposable
private bool _isDisposed = false;
public void Dispose()
{
Dispose(false);
}
private void Dispose(bool finalizing)
{
if (!_isDisposed)
{
// Close SessionFactory
_sessionFactory.Close();
_sessionFactory.Dispose();
// Flag as disposed.
_isDisposed = true;
if (!finalizing)
GC.SuppressFinalize(this);
}
}
#endregion
#region Methods
public INHibernateSession CreateSession()
{
return new NHibernateSession(CreateISession());
}
public ISession CreateISession()
{
ISession iSession;
lock (_sessionFactory)
{
iSession = _sessionFactory.OpenSession();
}
return iSession;
}
#endregion
#region Properties
public INHibernateSession Session
{
get
{
INHibernateSession session = ContextSession;
// If the thread does not yet have a session, create one.
if (session == null)
{
session = CreateSession();
// Save to CallContext.
ContextSession = session;
}
return session;
}
}
private INHibernateSession ContextSession
{
get
{
if (IsWebContext)
return (NHibernateSession)System.Web.HttpContext.Current.Items[_sessionContextKey];
else
return (NHibernateSession)System.Runtime.Remoting.Messaging.CallContext.GetData(_sessionContextKey);
}
set
{
if (IsWebContext)
System.Web.HttpContext.Current.Items[_sessionContextKey] = value;
else
System.Runtime.Remoting.Messaging.CallContext.SetData(_sessionContextKey, value);
}
}
private bool IsWebContext
{
get { return (System.Web.HttpContext.Current != null); }
}
#endregion
}
}
相关文章推荐
- Web项目下NHibernate的Session管理的解决方案
- [转]Web项目下NHibernate的Session管理的解决方案
- Maven Web项目配置Mybatis出现SqlSessionFactory错误的解决方案
- 解决方案:SSM+vue+webpack+vue-resource+vue-route路由项目验证session过期跳转至登陆界面
- web项目权限管理解决方案及shiro框架
- Javaweb项目session超时解决方案
- Asp.Net大型项目实践(4)-用NHibernate保存和查询我们的业务领域对象之NHibernate的Session管理与初始化(附源码)
- Asp.Net大型项目实践(4)-用NHibernate保存和查询我们的业务领域对象之NHibernate的Session管理与初始化(附源码)
- Maven Web项目配置Mybatis出现SqlSessionFactory错误的解决方案
- Web项目解决方案框架
- JavaWeb开发中的Session管理
- 微软项目管理解决方案解析
- 15款提高工作效率的 Web 项目管理工具
- web项目经理手册-风险管理
- 在同一个tomcat下,不同的web项目共享session
- 使用Jenkins启动maven作为项目构建管理工具的web项目
- 使用Jenkins启动maven作为项目构建管理工具的web项目
- 在同一个tomcat下,不同的web项目共享session
- “无法从web服务器获取项目文件”解决方案
- IntelliJ IDEA 12创建Maven管理的Java Web项目(图解)