WinForm C# 中的 Nhibernate 会话



我正处于winForm应用程序的中间,并且正在使用MVP作为体系结构和NHIBERNATE作为ORM

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

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);
    }
}

如何转换该代码,以便我可以存储每个表单的会话。谢谢

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

首先创建一个 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上,您可以访问SesssionStorage:

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();
    }

最新更新