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.