开发者

NHibernate - "Session is closed! Object name: 'ISession'

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:

pu开发者_如何转开发blic 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.


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜