我正在用多个 session 工厂重构我们的 UnitOfWork 代码。我们的 UoW 正在遍历所有 session 工厂,打开它们并绑定(bind)到上下文——这就是问题所在。
public void InitializeSessions()
{
foreach (ISessionFactory sessionFactory in _sessionFactories)
{
if ( NHibernate.Context.CurrentSessionContext.HasBind(sessionFactory))
{
continue;
}
ISession session = sessionFactory.OpenSession();
NHibernate.Context.CurrentSessionContext.Bind(session);
session.BeginTransaction();
}
}
这个 UoW 必须是通用的——这意味着它可以被 WCF、Web 或单元测试使用。因此,对于 WCF 应用程序,我们在 nh 配置 session 上下文中将其设置为“WcfOperationSessionContext”,例如 Web。 “ManagedWebSessionContext”。发生的问题是我们不能使用类 CurrentSessionContext 的静态方法,因为方法“Bind”需要 ISessionFactoryImplementor 继承自“CurrentSessionContext”。经过一番搜索,我们发现在示例中它直接调用了在 nh 配置文件中设置的上下文,但在互联网的其他实现中,它们严格使用“CurrentSessionContext”。
这到底应该怎么做?如果我们应该直接调用在 nh config 中配置的“ICurrentSessionContext”的上下文实现,还是始终使用“CurrentSessionContext”(这不像我提到的那样工作)?
最佳答案
对于 CurrentSessionContext,您希望根据文档使用 WebSessionContext 而不是 ManagedWebSessionContext:http://nhibernate.info/doc/nh/en/index.html#architecture-current-session
关于c# - NHibernate 上的 CurrentSessionContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11755414/