我最近从直接使用 ISession 转移到了包装的 ISession、工作单元类型模式。
我曾经使用 SQL Lite(内存中)对此进行测试。我有一个简单的帮助类,它配置我的 SessionFactory,创建一个 ISession,然后使用 SchemaExport 构建模式,然后返回我的 ISession,模式一直存在,直到我关闭会话。我对此稍作更改,现在配置一个 SessionFactory,创建一个 ISession,构建模式,并将工厂传递给我的 NHibernateUnitOfWork 并将其返回给我的测试。
var databaseConfiguration =
SQLiteConfiguration.Standard.InMemory()
.Raw("connection.release_mode", "on_close")
.Raw("hibernate.generate_statistics", "true");
var config = Fluently.Configure().Database(databaseConfiguration).Mappings(
m =>
{
foreach (var assembly in assemblies)
{
m.FluentMappings.AddFromAssembly(assembly);
m.HbmMappings.AddFromAssembly(assembly);
}
});
Configuration localConfig = null;
config.ExposeConfiguration(x =>
{
x.SetProperty("current_session_context_class", "thread_static"); // typeof(UnitTestCurrentSessionContext).FullName);
localConfig = x;
});
var factory = config.BuildSessionFactory();
ISession session = null;
if (openSessionFunction != null)
{
session = openSessionFunction(factory);
}
new SchemaExport(localConfig).Execute(false, true, false, session.Connection, null);
UnitTestCurrentSessionContext.SetSession(session);
var unitOfWork = new NHibernateUnitOfWork(factory, new NHibernateUTCDateTimeInterceptor());
return unitOfWork;
在内部,NHibernateUnitOfWork 需要获取用于创建模式的 ISession,否则内存数据库实际上不会有模式,所以这是它调用来获取 ISession 的方法。
private ISession GetCurrentOrNewSession()
{
if (this.currentSession != null)
{
return this.currentSession;
}
lock (this)
{
if (this.currentSession == null)
{
// get an existing session if there is one, otherwise create one
ISession session;
try
{
session = this.sessionFactory.GetCurrentSession();
}
catch (Exception ex)
{
Debug.Write(ex.Message);
session = this.sessionFactory.OpenSession(this.dateTimeInterceptor);
}
this.currentSession = session;
this.currentSession.FlushMode = FlushMode.Never;
}
}
问题是它this.sessionFactory.GetCurrentSession
总是抛出一个异常,说ICurrentSessionContext
没有注册。
我尝试了很多不同的方法来设置属性和不同的值(如您在上面看到的,“thread_static”和我自己的ICurrentSessionContext
),但似乎都没有。
任何人有任何建议