NHibernate thread in session is unsafe

Source: Internet
Author: User
Tags httpcontext

The session in NHibernate is thread insecure and has some impact on performance each time a database operation requests a session. Thread safety can be implemented easily in Windows applications through the [ThreadStatic] feature, whereas in the Web, thread safety can be achieved by using the session with the request HttpContext binding, and the user is currently requesting only one session. The code is as follows:

ISessionManage.cs

Using System;
Using NHibernate;

Namespace Commercial.Jwsoft.Framework.Persistence.SessionManage
{
<summary>
Function: Mainly used to encapsulate the third party class library operation database session class, is mainly used to encapsulate NHibernate in the session
</summary>
public interface Isessionmanage
{
<summary>
Get an instance of the session
</summary>
<returns> returns the class that implements the Nhibernate.isession interface </returns>
ISession Get ();

<summary>
Set up an instance of the session
</summary>
<param name= "Session" > Implementation of Nhibernate.isession Interface class </param>
void Set (ISession session);
}
}

--------------------------------------------

WebNHSession.cs

Using System;
Using System.Web;
Using NHibernate;

Namespace Commercial.Jwsoft.Framework.Persistence.SessionManage
{
<summary>
Features: This class is for Web applications, and the session provided by NHibernate has two drawbacks:
On the one hand, thread insecurity, and on the other hand, creating a session per database operation has an impact on program performance.
So by binding the session to HttpContext, each user has a unique session, and
Close the session at the end of the user's request and release it yourself.
</summary>
public class Webnhsession:isessionmanage
{
Public Webnhsession ()
{

}

<summary>
Gets the class instance that implements the Nhibernate.isession interface stored in the HttpContext
</summary>
<returns> implements a class instance of the Nhibernate.isession interface, which returns null</returns> when the user has not called the set method before
Public ISession Get ()
{
Return (ISession) httpcontext.current.items[sessionconfigmanage.sessionsourceitemname];
}

<summary>
Store class instances that implement the Nhibernate.isession interface into HttpContext
</summary>
<param name= "Session" > Implementing class instances of Nhibernate.isession interfaces </param>
public void Set (ISession session)
{
if (session! = NULL)
{
HTTPCONTEXT.CURRENT.ITEMS.ADD (Sessionconfigmanage.sessionsourceitemname, session);
}
Else
{
HttpContext.Current.Items.Remove (Sessionconfigmanage.sessionsourceitemname);
}
}
}
}
---------------------------------------------

WinFormNHSession.cs

Using System;
Using NHibernate;

Namespace Commercial.Jwsoft.Framework.Persistence.SessionManage
{
<summary>
Features: This class is for Windows apps, and the session provided by NHibernate has two defects:
On the one hand, thread insecurity, and on the other hand, creating a session per database operation has an impact on program performance.
Therefore, a thread variable gets a thread-safe instance of a NHibernate session, and the thread variable is freed after it is used.
</summary>
public class Winformnhsession:isessionmanage
{
[ThreadStatic]
private static ISession _threadsession = null;

Public Winformnhsession ()
{
}

<summary>
Gets the class instance that implements the Nhibernate.isession interface stored in a thread variable
</summary>
<returns> implements a thread-safe class instance of the Nhibernate.isession interface, which returns null</returns> when the user has not called the set method before
Public ISession Get ()
{
if (_threadsession! = null)
{
if (_threadsession.isconnected)
{
_threadsession.reconnect ();
}
}
return _threadsession;
}

<summary>
Store a class instance that implements the Nhibernate.isession interface into a thread variable
</summary>
<param name= "Session" > Implementing class instances of Nhibernate.isession interfaces </param>
public void Set (ISession session)
{
if (_threadsession.isconnected)
{
Session. Disconnect ();
}
_threadsession = session;
}
}
}

SessionFactory.cs

Using System;
Using System.Runtime.Remoting;
Using NHibernate;


Namespace Commercial.Jwsoft.Framework.Persistence.SessionManage
{
<summary>
Function: Manage multiple class factories that implement Isessionmanage interface, dynamically create session based on read class name information to be loaded
</summary>
public class Sessionfactory
{
private static ISession session = NULL;
private static Isessionmanage sessionmanage = null;

Static Sessionfactory ()
{
Init ();
}

<summary>
Gets the session instance that implements the Nhibernate.isession interface
</summary>
<returns> returns class instances that implement the Nhibernate.isession interface </returns>
public static ISession getsession ()
{
Session = Sessionmanage.get ();

if (session = = NULL)
{
Session = Nhibernatesession.getnhibernatesession ();
Sessionmanage.set (session);
}

return session;
}

private static void Init ()
{
System.Reflection.Assembly-System.Reflection.Assembly.Load (Sessionconfigmanage.assemblyname);
Sessionmanage = (isessionmanage). CreateInstance (Sessionconfigmanage.sessionsourceitemname);
}
}
}
----------------------------------------------

NHibernateSession.cs

Using System;
Using System.Data;
Using System.Collections.Generic;
Using System.Text;
Using NHibernate;
Using Nhibernate.cfg;

Namespace Commercial.Jwsoft.Framework.Persistence.SessionManage
{
<summary>
Function: Load Embedded resource (XML config file), open a sessionfactory, get NHibernate Session instance
</summary>
public class Nhibernatesession
{
private static Configuration cfg = null;
private static isessionfactory sessionfactory = null;

Static Nhibernatesession ()
{
CFG = new Configuration (). Configure ();
Sessionfactory = cfg. Buildsessionfactory ();
}

<summary>
Get the session instance of NHibernate
</summary>
<returns></returns>
public static ISession Getnhibernatesession ()
{
return Sessionfactory.opensession ();
}
}
}
---------------------------------------------

SessionConfigManage.cs

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Configuration;

Namespace Commercial.Jwsoft.Framework.Persistence.SessionManage
{
<summary>
Features: Dynamically create class instances based on the different application environments of the class library (Windows or Web Apps)
Date: 2006-08-24
Kuo Shaohong
</summary>
public class Sessionconfigmanage
{
Private Const string session_item_name = "Sessionitemname";
private static Object _locker = new Object ();
private static string _sessionitemname = String. Empty;
private static string _AssemblyName = String. Empty;

Static Sessionconfigmanage ()
{
String configstring = Configurationmanager.appsettings[session_item_name];
string[] arr = configstring.split (', ');
_sessionitemname = arr[0];
_AssemblyName = arr[1];
}
<summary>
Gets the information in the configuration file named Session_item_name configuration section that records the full name of the Sessionmanage to load
</summary>
<returns> the name of the class that implements the Isessionmanage interface </returns>
public static string Sessionsourceitemname
{
Get
{
Lock (_locker)
{
return _sessionitemname;
}
}
}

<summary>
Gets the information in the configuration file named Session_item_name configuration section that records the full name of the Sessionmanage to load
</summary>
<returns> assembly name of the class that implements the Isessionmanage interface </returns>
public static string AssemblyName
{
Get
{
Lock (_locker)
{
return _assemblyname;
}
}
}
}
}

The configuration section in the Web. config file is as follows:

<appSettings>
<!---->
<!--gets the class name of the session loaded in the Web App--
<add key= "Sessionitemname" value= "Commercial.Jwsoft.Framework.Persistence.SessionManage.WebNHSession, Jwframework "/>
<!--the class name to get session loaded in Windows apps--
<!--<add key= "Sessionitemname" value= " Commercial.jwsoft.framework.persistence.sessionmanage.winformnhsession,jwframework "/>-->
</appSettings>

Add the following code to the Global.asax:

<summary>
The connection used to close the session of the user request when the user disconnects the request
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
void Session_End (object sender, EventArgs e)
{
Nhibernate.isession session = Commercial.Jwsoft.Framework.Persistence.SessionManage.SessionFactory.GetSession ();
if (session! = NULL)
{
Session. Close ();
}

}

NHibernate thread in session is unsafe

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.