使用WebSessionContext/CurrentSessionContext初始化Isession
-
11-10-2019 - |
题
我正在使用NHIBERNATE 3启动一个新项目,并且我正在尝试将CurrentSessionContext API与WebSessionContext一起管理我的ISESSION对象。
在以前的项目中,我总是自己管理自己,因此每当需要一个Isession对象时,我都会创建它并存储在httpcontext.items集合中。非常简单,但是使用本机解决方案(CurrentSessionContext)似乎是该新项目的最佳选择。
当我管理对象时,我能够在其上进行懒惰的初始化,这意味着我只会在需要时打开一个会话,而不是在每个请求中,因为我可能不需要它,并且会通过打开所有内容来浪费资源/时间时间。
是否有一种简单的方法可以使用CurrentSessessesseveContext API做到这一点?
这是我在httpmodule中使用的代码:
public class ContextualSessionModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
public void Dispose()
{
}
private static void context_BeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var context = application.Context;
BindSession(context);
}
private static void BindSession(HttpContext context)
{
// Create a new session (it's the beginning of the request)
var session = SessionBuilderFactory.CurrentSessionFactory.OpenSession();
// Tell NH session context to use it
CurrentSessionContext.Bind(session);
}
private static void context_EndRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var context = application.Context;
UnbindSession(context);
}
private static void UnbindSession(HttpContext context)
{
// Get the default NH session factory
var factory = SessionBuilderFactory.CurrentSessionFactory;
// Give it to NH so it can pull the right session
var session = CurrentSessionContext.Unbind(factory);
if (session == null) return;
session.Flush();
session.Close();
}
}
编辑
迭戈几乎把它钉了,但是我对此有所思考,我想起了我自己实施该控制权的主要原因:交易。
我是一个 洋葱架构 盖伊,所以我的域对象(知道何时开始交易的对象)无法访问基础架构,因此他们无法启动交易。
为了解决这个问题,我使用懒惰的初始化,并在打开会话时始终开始交易。当请求结束并且没有例外时,承诺就会发生。除此之外,即使在查询时,也有Ayende的建议始终使用交易。有什么想法吗?
解决方案
虽然没有 直接地 我认为回答您的问题: 为什么?
会话是一个轻巧的对象。如果您不使用它,它只是初始化了一些内部结构,但它不会打开数据库连接或其他任何内容。
周围有一些示例(仅Google),以避免为静态对象打开会话,以节省一些时间/内存。除此之外,除非您的分析表明它会伤害您的表现,否则这可能是不值得的。
更新:对于交易需求,请查看UNHADDINS中的CPBT实现。