Nhibernate- ASP.NET MVCを使用した単位テスト
-
08-10-2019 - |
質問
ASP.NET MVCアプリケーションの私のコントローラーは、Nhibnerateセッションの周りのラッパーであるIdatacontextに依存しているため、これを簡単に置き換えることができます。 Microsoft Unity IOCコンテナを使用して、クラスのコンストラクター内に依存関係を注入します。
最初にテストプロジェクト内でfakedatacontextを作成して、次のように正しい依存関係をセットアップしました。
public class BaseControllerTest {
[TestInitialize]
public void Init() {
// Create the ioc container
var container = new UnityContainer();
// Setup the common service locator (must come before any instance registered that use the common service locator such as membership provider)
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
// Configure the container
container.RegisterType<IDataContext, FakeDataContext>();
}
}
今、私がしなければならないのはこのクラスから継承することであり、すべてが正常に機能することですが、Fakedatacontextはテストを実行する最も正確な方法ではないと感じているので、SQLiteを使用してメモリセッションを作成しようとしています。上記を次のように変更しました。
public class BaseControllerTest {
private static Configuration _configuration;
[TestInitialize]
public void Init() {
// Create the ioc container
var container = new UnityContainer();
// Configure the container
container.RegisterType<ISessionFactory>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => {
return CreateSessionFactory();
}));
container.RegisterType<ISession>(new InjectionFactory(c => {
var sessionFactory = container.Resolve<ISessionFactory>();
var session = sessionFactory.OpenSession();
BuildSchema(session);
return session;
}));
container.RegisterType<IDataContext, NHibernateDataContext>();
}
private static ISessionFactory CreateSessionFactory() {
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.InMemory())
.Mappings(m => m.FluentMappings
.AddFromAssembly(Assembly.GetExecutingAssembly())
.Conventions.AddFromAssemblyOf<EnumConvention>())
.ExposeConfiguration(c => _configuration = c)
.BuildSessionFactory();
}
private static void BuildSchema(ISession session) {
var export = new SchemaExport(_configuration);
export.Execute(true, true, false, session.Connection, null);
}
}
ただし、これにより、「SessionFactoryの作成中に使用されている」というエラーが発生します。これは、マッピングが探しているエンティティがテストプロジェクトとは異なるプロジェクトにあるためだと思ったので、assembly.loadfile( "c:.. myassembly.dll")と言ってみましたが、これはまだ機能しませんでした。
次の記事を使用したことに注意してください http://www.mohundro.com/blog/commentView,GUID,FA72FF57-5C08-49FA-979E-C732DF2BF5F8.ASPX 助けてくださいが、それは私が探しているものではありません。
誰かが助けてくれたら感謝します。ありがとう
解決
問題が解決しました。 SQLite DLLへの参照を追加する必要がありました。また、セッションをセッション工場と同じようにCoanterercontrolledlifetimemanagerを使用するためにセッションを変更しました。これを行うためのより効率的な方法がある場合は、私を修正してください。