【问题标题】:Nhibernate Session in WinForm C#WinForm C# 中的休眠会话
【发布时间】:2017-10-08 17:29:48
【问题描述】:

我在一个 winForm 应用程序的中间,我正在使用 MVP 作为架构 和 NHIBERNATE 作为 ORM

到目前为止,一切都很好,但现在我想使用会话容器为我的 nh 会话存储和检索它们。 在 webform 中我使用 http 请求来存储主题没问题,但在 Winform 中我很困惑。 webform 的成本是 .

public class HttpSessionContainer : ISessionStorageContainer
{
    private string _sessionKey = "NhibernateSession";

    public ISession GetCurrentSession()
    {
        ISession nhSession = null;

        if (HttpContext.Current.Items.Contains(_sessionKey))
            nhSession = (ISession)HttpContext.Current.Items[_sessionKey];

        return nhSession;
    }

    public void Store(ISession session)
    {
        if (HttpContext.Current.Items.Contains(_sessionKey))
            HttpContext.Current.Items[_sessionKey] = session;
        else
            HttpContext.Current.Items.Add(_sessionKey, session);
    }
}

如何转换该代码,以便我可以按 Form 存储我的会话。 谢谢

【问题讨论】:

  • 我建议搜索有关“会话每会话”模式的信息。恕我直言,这将是在使用 MVP 模式的 Windows 窗体应用程序中管理 NHibernate 会话的理想方式。

标签: c# winforms session nhibernate mvp


【解决方案1】:

您可以使用静态类来创建会话存储:

首先创建一个SessionStorageFactory:

public static class SessionStorageFactory
{
    public static Dictionary<string, ISessionStorageContainer> _nhSessionStorageContainer = new Dictionary<string, ISessionStorageContainer>();
    public static ISessionStorageContainer GetStorageContainer(string key)
    {
        ISessionStorageContainer storageContainer = _nhSessionStorageContainer.ContainsKey(key) ? _nhSessionStorageContainer[key] : null;
        if (storageContainer == null)
        {
            if (HttpContext.Current == null)
            {
                storageContainer = new ThreadSessionStorageContainer(key);
                _nhSessionStorageContainer.Add(key, storageContainer);
            }
            else
            {
                storageContainer = new HttpSessionContainer(key);
                _nhSessionStorageContainer.Add(key, storageContainer);
            }
        }
        return storageContainer;
    }
}

然后在您的 GetCurrentSession 上,您可以访问您的 SessionStorage:

public ISession GetCurrentSession
    {
        get
        {
            ISessionStorageContainer sessionStorageContainer = SessionStorageFactory.GetStorageContainer(ConnectionName + ".SessionKey");
            ISession currentSession = sessionStorageContainer.GetCurrentSession();
            if (currentSession == null)
            {
                currentSession = GetNewSession();
                sessionStorageContainer.Store(currentSession);
            }
            return currentSession;
        }
    }

private ISession GetNewSession()
    {
        return GetSessionFactory().OpenSession();
    }

【讨论】:

    猜你喜欢
    • 2012-06-02
    • 2018-09-27
    • 2013-09-14
    • 1970-01-01
    • 2015-03-18
    • 2011-02-01
    • 1970-01-01
    相关资源
    最近更新 更多