最近、ISessionを直接使用することから、ラップされたISession、Unit-of-Workタイプのパターンに移行しました。
以前はSQLLite(メモリ内)を使用してこれをテストしていました。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
)、どれも機能していないようです。
誰でもアドバイスをもらいました