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

  • SEARCH
  • Home
  • 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 5981773
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T21:59:27+00:00 2026-05-22T21:59:27+00:00

I’m using NHibernate behind my ASP.NET MVC application and I’ve come across a frustrating

  • 0

I’m using NHibernate behind my ASP.NET MVC application and I’ve come across a frustrating problem when trying to save an object via an AJAX call. I am getting the usual:

Failed to lazily initialize a collection of role: [type] no session or session was closed

The problem is, as far as I can tell the session is not closed. I’m using an HttpModule to handle my sessions per the session per request pattern with NHibernate set to use the web current_session_context_class. Here’s the HttpModule:

public class NHHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.EndRequest += ApplicationEndRequest;
        context.BeginRequest += ApplicationBeginRequest;
    }

    public void ApplicationBeginRequest(object sender, EventArgs e)
    {
        CurrentSessionContext.Bind(SessionFactory.GetNewSession());
    }

    public void ApplicationEndRequest(object sender, EventArgs e)
    {
        var currentSession = CurrentSessionContext.Unbind(SessionFactory.GetSessionFactory());
        currentSession.Close();
        currentSession.Dispose();
    }

    public void Dispose()
    {
        // Do nothing
    }
}

My SessionFactory is pretty standard, too:

public static class SessionFactory
{
    private static ISessionFactory _sessionFactory;

    private static void Init()
    {
        _sessionFactory = Fluently.Configure() //Lots of other stuff here for NH config
            .BuildSessionFactory();
    }

    public static ISessionFactory GetSessionFactory()
    {
        if (_sessionFactory == null)
            Init();

        return _sessionFactory;
    }

    public static ISession GetNewSession()
    {
        return GetSessionFactory().OpenSession();
    }

    public static ISession GetCurrentSession()
    {
        return GetSessionFactory().GetCurrentSession();
    }
}

I’m using a unit of work for transactions, which is why I don’t open a transaction at the BeginRequest. Even so, I’ve tried that with no change in results.

I’m trying to save a Comment object to a User object via an AJAX post. Here is the controller code:

    [HttpPost, ValidateInput(false)]
    public ActionResult CreateCommentAsync(CommentCreateViewModel model)
    {
        if (!model.UserId.HasValue)
            return Content("false");

        var svc = DependencyResolver.Current.GetService<IPartnerUserService>();
        var user = svc.FindBy(model.UserId.Value, UserContext.Current.ActiveUser);

        // I put this in here as a test -- it throws the no-session error, too.            
        var count = user.Comments.Count();

        var comment = new Comment();
        comment.CommentText = model.CommentText;
        comment.DateCreated = DateTime.UtcNow;
        comment.CreatedBy = UserContext.Current.ActiveUser;

        // This is the original source of the error
        user.Comments.Add(comment);
        svc.Save(user, UserContext.Current.ActiveUser);

        return Content("true");
    }

I have debugged the application and confirmed that a session is created at the beginning of the request, and, most confusing, the SessionFactory.GetCurrentSession().IsOpen is true, even when I hit a breakpoint for the errors listed above.

Furthermore, the Comments list is populated when I render a view that displays a list of comments. I can’t figure out why it’s failing when I add it.

As if that weren’t enough, every once in a while, with no changes to the code, I don’t get the error and can successfully add a comment. I’m pulling my hair out…any ideas? This is certainly a session management issue, but I’ve gone over everything I can find online and by all accounts the way I’m doing session management is ok. Any ideas?

UPDATE:
I’ve tried a few additional tests, most notably whether the current session has the user object I’m trying to manipulate. It does. When I test like this:

if (!SessionFactory.GetCurrentSession().Contains(user))
    SessionFactory.GetCurrentSession().Refresh(user);

I get a result of true on the condition.

A commenter requested the code on the service, but for that particular call it doesn’t touch a session, it just verifies that the requesting user has permissions then sets up the detached criteria. The repository is then called within that service, and here’s that code:

public IEnumerable<T> FindBy(DetachedCriteria detachedCriteria) //Infrastructure.Querying.Query query)
{
    return detachedCriteria.GetExecutableCriteria(SessionFactory.GetCurrentSession()).Future<T>();
}

The reason I don’t think this code is the problem is that it’s exactly the same code called for the details view. I don’t have any lazy loading errors when I display the comments, and I do it the same way – I use the service to load the user object then do a foreach iteration through the list. I’ve NEVER had a problem doing that.

In case this was some sort of issue with the AJAX call, I also changed it to a full postback, but still got the same error.

I can’t for the life of me figure out what’s going on here.

  • 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. Editorial Team
    Editorial Team
    2026-05-22T21:59:28+00:00Added an answer on May 22, 2026 at 9:59 pm

    I finally discovered the reason for this error, but only by dumb luck. I’ll post the resolution in case it helps someone, but I can’t really offer any explanation why and will probably post a new question to see if someone can clear the air.

    You’ll note in my code I was calling my service like this:

    var user = svc.FindBy(model.UserId.Value, UserContext.Current.ActiveUser);
    

    That UserContext object is a static class with a session-stored Current instance that contains a property which is the current user record NHibernate object. Because of how NHibernate proxies properties, that UserContext.ActiveUser property had to do something like this whenever it was called:

    if (!SessionFactory.GetCurrentSession().Contains(ActiveUser))
        SessionFactory.GetCurrentSession().Refresh(ActiveUser);
    

    For some reason, it was this refresh process that was screwing things up. When I explicitly retrieved the active user instead of using the UserContext class, everything worked fine.

    I’ve since changed how I retrieve the active user so that it’s not using a session-stored instance and it’s working fine. I wish I knew exactly why, but I don’t!

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

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
I am currently running into a problem where an element is coming back from
I am using the SimpleRSS gem to parse a WordPress RSS feed. The only

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.