0
votes

I'm using NHibernate on a custom membership provider in a MVC3 application. Whenever I try to login though, I get the exception:

Session is closed! Object name: 'ISession'

The code in the membership provider looks like this:

ContractRepository repository;
public string UserDescription { get; set; }

public CustomSqlMembershipProvider() {
    this.repository = new ContractRepository(ProviderPortal.Persistance.NHibernateSessionStorage.RetrieveSession());
}

public override bool ValidateUser(string username, string password) {
    var user = repository.GetContractForUser(username);
    if (user == null)
        return false;
    else {
        UserDescription = user.Description;
        return true; //TODO: come back and add user validation.
    }
}

And here is the retrieve session methods:

public static ISession RetrieveSession() {
    HttpContext context = HttpContext.Current;
    if (!context.Items.Contains(CURRENT_SESSION_KEY)) OpenCurrent();
    var session = context.Items[CURRENT_SESSION_KEY] as ISession;
    return session;
}

private static void OpenCurrent() {
    ISession session = NHibernateConfiguration.CreateAndOpenSession();
    HttpContext context = HttpContext.Current;
    context.Items[CURRENT_SESSION_KEY] = session;
}

This is where the exception is happening:

public Contract GetContractForUser(string UserName) {
    return (Contract)session.CreateCriteria(typeof(Contract))
        .Add(Restrictions.Eq("Login", int.Parse(UserName))).UniqueResult();
}

Somewhere between the CustomSqlMembershipProvider constructor being called, and the ValidateUser method being called, the session is being closed. Any ideas? My other Controllers are injected with an open session via DI, but this one is giving me the hardest time.

1
Not to thread jack but this kind of nightmare with the session management with NHibernate is what made me stop actively developing with it. - Chris Marisic
@Chris: you should use Spring for managing transactions. - Tyler Treat
Session management is ridiculously easy to manage with NH... - Phill
@Phill try to do something complicated with it, like implement the long conversation pattern. - Chris Marisic

1 Answers

1
votes

Do you get this one consistently or on and off?

We were getting this using Spring.net for our DI and using OpenSessionInView

We had to add the following http module to change the storage options for the current thread.

public class SpringThreadStorageModule : IHttpModule
{
    static SpringThreadStorageModule()
    {
        LogicalThreadContext.SetStorage(new HybridContextStorage());
    }



    #region IHttpModule Members

    public void Dispose()
    {
        // do nothing
    }

    public void Init(HttpApplication context)
    {
        // we just need the staic init block.
    }

    #endregion
}