【发布时间】:2010-09-09 09:23:33
【问题描述】:
我需要在 MVC 中设置会话管理。这样做的正确方法是什么? 如何使用结构映射在 mvc 中设置 nhibernate 会话管理,所以我不明白:
会话已关闭 或者 在多个线程中使用单个 Session 可能是一个错误。
我目前的配置是: 在 GlobalAssax 中:
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
Bootstrapper.ConfigureStructureMap();
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
在我的 BootStrapper 中我这样做:
var cfg = NHibernateManager.Configuration(assembly);
For<Configuration>().Singleton().Use(cfg);
For<ISessionFactory>().Singleton().Use(cfg.BuildSessionFactory());
For<ISession>().HttpContextScoped().Use(ctx => ctx.GetInstance<ISessionFactory>().OpenSession());
我将 ISession 注入到我在应用层使用的存储库中。
编辑:如果我这样做会发生什么?: For().LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.PerRequest)).Use(ctx => ctx.GetInstance().OpenSession());
【问题讨论】:
-
您是否在应用程序中的任何位置调用 Dispose 或在会话周围使用 using 子句?如果是这样,请删除它,因为您让 StructureMap 处理生命周期。
标签: nhibernate model-view-controller structuremap