对于Web应用程序与后台的同事NHibernate的会话管理策略? [英] Nhibernate session management strategy for web application with background-workers?
问题描述
有关Web应用程序,它似乎是一个好办法来处理会话使用的设置<属性名=current_session_context_class> managed_web< /性>
,呼叫 CurrentSessionContext.Bind /拆散
在开始/ EndRequest。然后,我可以只使用 sessionFactory.GetCurrentSession()
存储库中的类。
For a web application, it seems like a good way to handle the session is to use the setting <property name="current_session_context_class">managed_web</property>
, call CurrentSessionContext.Bind/Unbind
on Begin/EndRequest. Then I can just use sessionFactory.GetCurrentSession()
in the repository class.
这所有的页面请求工作正常。但我有背景的工人做的东西,并使用相同的库类做的东西。这些没有一个Web请求中运行,从而使会话处理将无法正常工作。
This works fine for all page request. But I have background workers doing stuff and using the same repository classes to do stuff. These do not run within a web request, so that session handling won't work.
任何建议,这可怎么解决呢?
Any suggestions to how this can be solved?
推荐答案
我创造我自己的会话上下文类解决了这个问题:
I solved it by creating my own session context class:
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;
}
}
}
这篇关于对于Web应用程序与后台的同事NHibernate的会话管理策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!