如何在ASP.NET MVC应用程序中部署NHibernate ISession

时间:2010-01-24 21:08:10

标签: asp.net-mvc nhibernate isession

我已经在我的asp.net mvc应用程序中连接了NHibernate。

如果我不处理ISession,一切正常。但是我已经阅读过你应该处理的内容,但是当我这样做时,我得到随机的“会话已关闭”例外。

我正在用温莎将ISession注入我的其他物品。

这是我目前的NHModule:

public class NHibernateHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += context_BeginRequest;
        context.EndRequest += context_EndRequest;
    }

    static void context_EndRequest(object sender, EventArgs e)
    {
        CurrentSessionContext.Unbind(MvcApplication.SessionFactory);
    }

    static void context_BeginRequest(object sender, EventArgs e)
    {
        CurrentSessionContext.Bind(MvcApplication.SessionFactory.OpenSession());
    }

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

注册ISession:

container
  .Register(Component.For<ISession>()
     .UsingFactoryMethod(() =>  MvcApplication.SessionFactory.GetCurrentSession()).LifeStyle.Transient);

当我在模块中解除Unbind上的Dispose时会发生错误。由于我不断得到会话被关闭错误我认为这不是正确的方法,所以正确的方法是什么?

谢谢, 乔

3 个答案:

答案 0 :(得分:1)

Robert是正确的,Windsor在释放依赖它的组件时处理会话。 而不是拥有自己的HttpModule,我建议使用Windsor的PeressRequest生活方式进行ISession。

答案 1 :(得分:0)

在Windsor尝试处理会话之前,似乎有一些持有会话的对象被处理掉了。快速解决方法是彻底解决您的NHiberanteSessionFactory Dispose方法并检查会话是否已经关闭。

答案 2 :(得分:0)

我认为这篇文章应该有所帮助:Building a Desktop To-Do Application with NHibernate

现在我知道,这是一个桌面应用程序,但您可能会从这篇MSDN文章中获得启发。