gpt4 book ai didi

c# - 具有后台 worker 的 Web 应用程序的 Nhibernate session 管理策略?

转载 作者:太空狗 更新时间:2023-10-29 22:09:51 25 4
gpt4 key购买 nike

对于 Web 应用程序,处理 session 的一个好方法似乎是使用设置 <property name="current_session_context_class">managed_web</property> , 调用 CurrentSessionContext.Bind/Unbind在开始/结束请求上。然后我可以使用 sessionFactory.GetCurrentSession()在存储库类中。

这适用于所有页面请求。但我有后台工作人员做事并使用相同的存储库类做事。它们不在 Web 请求中运行,因此 session 处理将不起作用。

对于如何解决这个问题有什么建议吗?

最佳答案

我通过创建自己的 session 上下文类解决了这个问题:

public class HybridWebSessionContext : CurrentSessionContext
{
private const string _itemsKey = "HybridWebSessionContext";
[ThreadStatic] private static ISession _threadSession;

// This constructor should be kept, otherwise NHibernate will fail to create an instance of this class.
public HybridWebSessionContext(ISessionFactoryImplementor factory)
{
}

protected override ISession Session
{
get
{
var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
if (currentContext != null)
{
var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
var session = items[_itemsKey] as ISession;
if (session != null)
{
return session;
}
}

return _threadSession;
}
set
{
var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
if (currentContext != null)
{
var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
items[_itemsKey] = value;
return;
}

_threadSession = value;
}
}
}

关于c# - 具有后台 worker 的 Web 应用程序的 Nhibernate session 管理策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5854238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com