All*_*est 5 .net c# nhibernate sessionfactory
对于Web应用程序,似乎处理会话的一种好方法是使用设置<property name="current_session_context_class">managed_web</property>,调用CurrentSessionContext.Bind/UnbindBegin/EndRequest.然后我可以sessionFactory.GetCurrentSession()在存储库类中使用.
这适用于所有页面请求.但我有后台工作人员在做东西并使用相同的存储库类来做事情.这些不在Web请求中运行,因此会话处理将不起作用.
有关如何解决这个问题的任何建议?
All*_*est 15
我通过创建自己的会话上下文类来解决它:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)