refereshing页面时的NHibernate会话关闭 [英] NHibernate session is closed when refereshing page

查看:201
本文介绍了refereshing页面时的NHibernate会话关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我遇到的这几天另一个陌生的问题!我创建和使用NHibernate MVC 4应用程序。并添加名为[LoggingNHibernateSessionAttribute]在我的HomeController它为每个操作管理会话的筛选器属性。我跟着ASP.NET MVC4以及A preSS发布的网页API

This is another strange problem I've encountered this days!!! I've created and MVC 4 app using nhibernate. and added a filter attribute named [LoggingNHibernateSessionAttribute] on my HomeController which manages session for each action. I've followed 'ASP.NET MVC4 and the Web API published by Apress'.

public class LoggingNHibernateSessionAttribute : ActionFilterAttribute
{
    private readonly IActionLogHelper _actionLogHelper;
    private readonly IActionExceptionHandler _actionExceptionHandler;
    private readonly IActionTransactionHelper _actionTransactionHelper;

    public LoggingNHibernateSessionAttribute()
        : this(WebContainerManager.Get<IActionLogHelper>(),
        WebContainerManager.Get<IActionExceptionHandler>(),
        WebContainerManager.Get<IActionTransactionHelper>())
    {
    }

    public LoggingNHibernateSessionAttribute(
        IActionLogHelper actionLogHelper,
        IActionExceptionHandler actionExceptionHandler,
        IActionTransactionHelper actionTransactionHelper)
    {
        _actionLogHelper = actionLogHelper;
        _actionExceptionHandler = actionExceptionHandler;
        _actionTransactionHelper = actionTransactionHelper;
    }

    public override void OnActionExecuting(ActionExecutingContext actionExectingContext)
    {
        _actionLogHelper.LogEntry(actionExectingContext.ActionDescriptor);
        _actionTransactionHelper.BeginTransaction();
    }

    public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
    {
        _actionTransactionHelper.EndTransaction(actionExecutedContext);
        _actionTransactionHelper.CloseSession();
        _actionExceptionHandler.HandleException(actionExecutedContext);
        _actionLogHelper.LogExit(actionExecutedContext.ActionDescriptor);
    }
}

ActionTransactionHelper

ActionTransactionHelper

  public class ActionTransactionHelper : IActionTransactionHelper
{
    private readonly ISessionFactory _sessionFactory;
    private readonly ICurrentSessionContextAdapter _currentSessionContextAdapter;

    public ActionTransactionHelper(
        ISessionFactory sessionFactory,
        ICurrentSessionContextAdapter currentSessionContextAdapter)
    {
        _sessionFactory = sessionFactory;
        _currentSessionContextAdapter = currentSessionContextAdapter;
    }

    public void BeginTransaction()
    {
        var session = _sessionFactory.GetCurrentSession();
        if (session != null)
        {
            session.BeginTransaction();
        }
    }

    public bool TransactionHandled { get; private set; }

    public void EndTransaction(ActionExecutedContext filterContext)
    {
        var session = _sessionFactory.GetCurrentSession();

        if (session == null) return;
        if (!session.Transaction.IsActive) return;

        if (filterContext.Exception == null)
        {
            session.Flush();
            session.Transaction.Commit();
        }
        else
        {
            session.Transaction.Rollback();
        }

        TransactionHandled = true;
    }

    public bool SessionClosed { get; private set; }

    public void CloseSession()
    {
        if (_currentSessionContextAdapter.HasBind(_sessionFactory))
        {
            var session = _sessionFactory.GetCurrentSession();
            session.Close();
            session.Dispose();
            _currentSessionContextAdapter.Unbind(_sessionFactory);

            SessionClosed = true;
        }
    }
}

运行应用程序时,我可以保存在数据库中的一个实体。但是当我点击刷新按钮,并抛出异常指示会话关闭。

when run the app, I can save an entity in the dataBase. but when I hit refresh button and exception thrown indication session is closed.

我不知道为什么会这样。 (我搜索,发现这个 NHibernate的投掷会话关闭但没能解决我的问题)。

I don't know why this happens. (I searched and find this Nhibernate throwing Session is closed but couldn't solve my problem).

在我NinjectConfigurator我加inRequestScope(),以所有注射,但没有答案。我查了一下,当我刷新页面会话将被打开。但我donnow为什么说会话关闭?!

in my NinjectConfigurator I added inRequestScope() to all of injections but no answer. I checked when I refresh the page session will be opened. but I donnow why it say session is closed?!

更新:

当我第一次运行应用程序。我可以创建一个新的成员。但是当我打的刷新按钮,该会话将被意外关闭!
第一次运行:

when I first run the app. I can create a new member. but when I hit the refresh button, the session will be closed unexpectedly!! first run:


  1. 一切正常

击中刷新按钮后:


  1. 一个新的会话绑定到当前上下文。

  2. 新的会话将被注入该库(会话是打开的)

  3. 的ActionTransactionHelper调用的BeginTransaction()
    4- customMembership的createUser(....)呼吁
    5但当称为存储库中的会话_userRepositoy.save(用户)关闭!!!!

请注意:但仍endTransaction和closeSession不叫。但是怎么会被关闭?
 如果我评论在onActionExecute closeSession()()。会议送花儿给人是开放的,一切都很好炒菜锅,如果刷新页面。
 我查了很多,想我知道不同的方式。它只是发生在第二次我想要做的CRUD操作我customMembership。

note:but when still endTransaction and closeSession isn't called. but how session is closed? if I comment closeSession() in onActionExecute(). session alway is open and everything woks well if refresh the page. I checked a lot and tried different way I knew. it only happens when for the second time I want to do CRUD operations with my customMembership.

其他实体它就像一个魅力!

我已经upoaded我的样本code。测试只需要创建空数据库和更改连接字符串。然后去到localhost: * / API /类别(用户,并通过不要求)

for other entities it works like a charm! I have upoaded my sample code. for testing just create and empty database and change connection string. then go to localHost:*/api/categories (user and pass doesn't required)

下载示例项目:
大小:47 MB
https://www.dropbox.com/s/o63wjng5f799fii/Hashem-MVC4ServicesBook.rar

大小:54 MB
ZIP格式: https://www.dropbox.com/s/smrsbz4cbtznx1y/Hashem- MVC4ServicesBook2.zip

推荐答案

这里一个非常重要的事情,可能是NHibernate的性质。该NHibernate和它的会话是ASP.NET MVC活得更长,那么可以预期。我的意思是,不仅里面的

A very important thing here, could be the nature of the NHibernate. The NHibernate and its Session are in the ASP.NET MVC living longer, then could be expected. I mean not only inside of the


  • ActionExecuting(控制器操作开始)

  • ActionExecuted(查看或重定向叫)

会议实际上还必须度过的渲染的阶段。因为,我们可以在行动(),但它集加载一些的代理的,可能是懒洋洋地查看渲染。因此,即使在这些阶段会话必须打开的(从请求开始时同一个Session)

Session in fact must live also through the phase of rendering. Because, we could load some proxy in the "Action()" but its collection, could be lazily loaded only during the View rendering. So even in these phases Session must be opened (the same Session from the request begining)


  • ResultExecuting(代理可能会开始仅此加载)

  • ResultExecuted(几乎全部完成,让我们关闭会话)

其他的话... 保持会话打开throught完整的请求即可。从授权,直到内容的呈现方式。

Other words... keep the session opened throught the complete Request. From authorization untill the content is rendered.

请注意:Anohter提示,的只是为了确保一切正常的,我使用的这个场景的(也许你做的一样好)的:

NOTE: Anohter hint, just to be sure that all is ok, I am using this scenario (maybe you do as well):


  1. 客户端窗体即将数据发送到服务器。该方法是POST,操作是更新()

  2. 发送FORM即将服务器,更新行动()被triggerred - 所有交易的东西到位(如上所述)

  3. 一旦NHibernate的持续数据到数据库,更新()动作结束,被重定向到行动

    • 详细()如果一切正常或

    • 编辑(),如果出现错误

  1. Client FORM is about to send the data to server. The method is POST, the Action is Update()
  2. Sent FORM is coming to server, Action Update() is triggerred - all the transactions stuff is in place (as described above)
  3. Once NHibernate persists the data into DB, the Update() action ends, and is redirected to action
    • Detail() if all is ok or
    • Edit() if something goes wrong

事实上,步骤的 1 的是行动之一详细信息修改。在这种情况下,我们就已经面临这个问题...

In fact, the step 1. was one of the Actions Detail or Edit. In this case, we would face this issue already...

这篇关于refereshing页面时的NHibernate会话关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆