3

正如我在标题中所说,我想为每个 Web 请求实现会话。我的会话提供程序是这样配置的(我对更改此配置不感兴趣。)

    public class SessionProvider
    {
        public static SessionProvider Instance { get; private set; }
        private static ISessionFactory _SessionFactory;

        static SessionProvider()
        {
            var provider = new SessionProvider();
            provider.Initialize();
            Instance = provider;
        }

        private SessionProvider()
        {

        }

        private void Initialize()
        {
            string csStringName = "ConnectionString";
            var cfg = Fluently.Configure()
                ....ommiting mappings and db conf.
                .ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
                .BuildConfiguration();
            _SessionFactory = cfg.BuildSessionFactory();    
        }

        public ISession OpenSession()
        {
            return _SessionFactory.OpenSession();
        }

        public ISession GetCurrentSession()
        {
            return _SessionFactory.GetCurrentSession();
        }
    }

在 Global.asax.cs 中,我有以下与每个 web req 的会话相关的代码。

private static ISessionFactory SessionFactory { get; set; }

    protected void Application_Start()
    {
        SessionFactory = MyDomain.SessionProvider.Instance.OpenSession().SessionFactory;

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var session = SessionFactory.OpenSession();
        CurrentSessionContext.Bind(session);
    }

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        var session = CurrentSessionContext.Unbind(SessionFactory);
        session.Dispose();
    }

在调试我的 webapp 时出现错误:没有配置当前会话上下文。 ErrorMessage 引用 global.asax 行 CurrentSessionContext.Bind(session);

更新已 添加.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web")) ,现在我在从我的控制器中检索数据时收到错误消息,如下所示 错误消息:会话已关闭!对象名称:'ISession'。

控制器代码:

using (ISession session = SessionProvider.Instance.GetCurrentSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    data = session.QueryOver<Object>()
                       ...ommiting

                    transaction.Commit();
                    return PartialView("_Partial", data);
                }

            }    
4

1 回答 1

5

第一个问题

你需要在你的 nhibernate 配置部分配置它:

<property name="current_session_context_class">web</property>

我目前也在做这样的事情:

if (!CurrentSessionContext.HasBind(SessionFactory))
{
    CurrentSessionContext.Bind(SessionFactory.OpenSession());
}

第二个问题

流畅地修改配置请看下面的文章:currentsessioncontext fluent nhibernate怎么做?

第三个问题

您将关闭会话两次。

using (ISession session = SessionProvider.Instance.GetCurrentSession()) 

关闭您的会话。然后你又做了一次Application_EndRequest。如果您还有其他问题,请发布一个新问题。

于 2012-05-21T19:05:34.733 回答