Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 167015
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T12:11:59+00:00 2026-05-11T12:11:59+00:00

I’ve been using NHibernate for a while now and have found from time to

  • 0

I’ve been using NHibernate for a while now and have found from time to time that if I try to request two pages simultaniously (or as close as I can) it will occasionally error. So I assumed that it was because my Session management was not thread safe.

I thought it was my class so I tried to use a different method from this blog post http://pwigle.wordpress.com/2008/11/21/nhibernate-session-handling-in-aspnet-the-easy-way/ however I still get the same issues. The actual error I am getting is:

Server Error in '/AvvioCMS' Application. failed to lazily initialize a collection, no session or session was closed Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.  Exception Details: NHibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed 

Either that or no datareader is open, but this is the main culprit.

I’ve placed my session management class below, can anyone spot why I may be having these issues?

public interface IUnitOfWorkDataStore {     object this[string key] { get; set; } }       public static Configuration Init(IUnitOfWorkDataStore storage, Assembly[] assemblies)     {         if (storage == null)             throw new Exception("storage mechanism was null but must be provided");          Configuration cfg = ConfigureNHibernate(string.Empty);         foreach (Assembly assembly in assemblies)         {             cfg.AddMappingsFromAssembly(assembly);         }          SessionFactory = cfg.BuildSessionFactory();         ContextDataStore = storage;          return cfg;     }      public static ISessionFactory SessionFactory { get; set; }     public static ISession StoredSession     {         get         {             return (ISession)ContextDataStore[NHibernateSession.CDS_NHibernateSession];         }         set         {             ContextDataStore[NHibernateSession.CDS_NHibernateSession] = value;         }     }      public const string CDS_NHibernateSession = "NHibernateSession";     public const string CDS_IDbConnection = "IDbConnection";      public static IUnitOfWorkDataStore ContextDataStore { get; set; }      private static object locker = new object();     public static ISession Current      {         get          {             ISession session = StoredSession;                          if (session == null)              {                 lock (locker)                 {                     if (DBConnection != null)                         session = SessionFactory.OpenSession(DBConnection);                     else                         session = SessionFactory.OpenSession();                      StoredSession = session;                 }             }              return session;         }         set         {             StoredSession = value;         }     }      public static IDbConnection DBConnection     {         get         {             return (IDbConnection)ContextDataStore[NHibernateSession.CDS_IDbConnection];         }         set         {             ContextDataStore[NHibernateSession.CDS_IDbConnection] = value;         }     }  } 

And the actual store I am using is this:

public class HttpContextDataStore : IUnitOfWorkDataStore {     public object this[string key]     {         get { return HttpContext.Current.Items[key]; }         set { HttpContext.Current.Items[key] = value; }     } } 

I initialize the SessionFactory on Application_Start up with:

NHibernateSession.Init(new HttpContextDataStore(), new Assembly[] {                  typeof(MappedClass).Assembly}); 

Update

Thanks for your advice. I have tried a few different things to try and simplify the code but I am still running into the same issues and I may have an idea why.

I create the session per request as and when it is needed but in my global.asax I am disposing of the session on Application_EndRequest. However I’m finding the Application_EndRequest is being fired more than once while I am in debug at the end of loading a page. I thought that the event is only suppose to fire once at the very end of the request but if it isn’t and some other items are trying to use the Session (which is what the error is complaining about) for whatever weird reason that could be my problem and the Session is still thread safe it is just being disposed of to early.

Anyone got any ideas? I did a google and saw that the VS development server does cause issues like that but I am running it through IIS.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T12:12:00+00:00Added an answer on May 11, 2026 at 12:12 pm

    While I haven’t seen your entire codebase or the the problem you’re trying to solve, a rethinking of how you are using NHibernate might be in order. From the documentation:

    You should observe the following practices when creating NHibernate Sessions:

    • Never create more than one concurrent ISession or ITransaction instance per database connection.

    • Be extremely careful when creating more than one ISession per database per transaction. The ISession itself keeps track of updates made to loaded objects, so a different ISession might see stale data.

    • The ISession is not threadsafe! Never access the same ISession in two concurrent threads. An ISession is usually only a single unit-of-work!

    That last bit is the most relevant (and important in the case of a multithreaded environment) to what I’m saying. An ISession should be used once for a small atomic operation and then disposed. Also from the documentation:

    An ISessionFactory is an expensive-to-create, threadsafe object intended to be shared by all application threads. An ISession is an inexpensive, non-threadsafe object that should be used once, for a single business process, and then discarded.

    Combining those two ideas, instead of storing the ISession itself, store the session factory since that is the ‘big’ object. You can then employ something like SessionManager.GetSession() as a wrapper to retrieve the factory from the session store and instantiate a session and use it for one operation.

    The problem is also less obvious in the context of an ASP.NET application. You’re statically scoping the ISession object which means it’s shared across the AppDomain. If two different Page requests are created within that AppDomain’s lifetime and are executed simultaneously, you now have two Pages (different threads) touching the same ISession which is not safe.

    Basically, instead of trying to keep a session around for as long as possible, try to get rid of them as soon as possible and see if you have better results.

    EDIT:

    Ok, I can see where you’re trying to go with this. It sounds like you’re trying to implement the Open Session In View pattern, and there a couple different routes you can take on that:

    If adding another framework is not an issue, look into something like Spring.NET. It’s modular so you don’t have to use the whole thing, you could just use the NHibernate helper module. It supports the open session in view pattern. Documentation here (heading 21.2.10. ‘Web Session Management’).

    If you’d rather roll your own, check out this codeproject posting by Bill McCafferty: ‘NHibernate Best Practices’. Towards the end he describes implementing the pattern through a custom IHttpModule. I’ve also seen posts around the Internet for implementing the pattern without an IHttpModule, but that might be what you’ve been trying.

    My usual pattern (and maybe you’ve already skipped ahead here) is use a framework first. It removes lots of headaches. If it’s too slow or doesn’t fit my needs then I try to tweak the configuration or customize it. Only after that do I try to roll my own, but YMMV. 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 122k
  • Answers 123k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Use this official guide: http://wiki.eclipse.org/Getting_started_with_CDT_development May 12, 2026 at 12:54 am
  • Editorial Team
    Editorial Team added an answer It looks like Serviced Components holds the key to my… May 12, 2026 at 12:54 am
  • Editorial Team
    Editorial Team added an answer Are you sure that you can get anything except the… May 12, 2026 at 12:54 am

Related Questions

I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I am currently running into a problem where an element is coming back from
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.