我想在我的ASP.NET MVC 2应用程序中使用NHibernate的Contextual Sessions,但我很难找到如何正确执行此操作的指导。
我对每个请求的会话感兴趣。
答案 0 :(得分:1)
如果我以正确的方式这样做,请告诉我。以下是我提出的建议:
<强> Global.asax中强>
public class MvcApplication : NinjectHttpApplication
{
public MvcApplication()
{
NHibernateProfiler.Initialize();
EndRequest += delegate { NHibernateHelper.EndContextSession(Kernel.Get<ISessionFactory>()); };
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
{
StandardKernel kernel = new StandardKernel();
kernel.Load(AppDomain.CurrentDomain.GetAssemblies());
return kernel;
}
}
<强> NHibernateHelper 强>
public class NHibernateHelper
{
public static ISessionFactory CreateSessionFactory()
{
var nhConfig = new Configuration();
nhConfig.Configure();
return Fluently.Configure(nhConfig)
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Reservation>()
.Conventions.Add(ForeignKey.EndsWith("Id")))
#if DEBUG
.ExposeConfiguration(cfg =>
{
new SchemaExport(cfg)
.SetOutputFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "schema.sql"))
.Create(true, false);
})
#endif
.BuildSessionFactory();
}
public static ISession GetSession(ISessionFactory sessionFactory)
{
ISession session;
if (CurrentSessionContext.HasBind(sessionFactory))
{
session = sessionFactory.GetCurrentSession();
}
else
{
session = sessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
return session;
}
public static void EndContextSession(ISessionFactory sessionFactory)
{
var session = CurrentSessionContext.Unbind(sessionFactory);
if (session != null && session.IsOpen)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
{
// an unhandled exception has occurred and no db commit should be made
session.Transaction.Rollback();
}
}
finally
{
session.Dispose();
}
}
}
}
<强> NHibernateModule 强>
public class NHibernateModule : NinjectModule
{
public override void Load()
{
Bind<ISessionFactory>().ToMethod(x => NHibernateHelper.CreateSessionFactory()).InSingletonScope();
Bind<ISession>().ToMethod(x => NHibernateHelper.GetSession(Kernel.Get<ISessionFactory>()));
}
}
答案 1 :(得分:1)
我们对bigglesby的态度略有不同,我并不是说他的错,或者说我们是完美的。
在我们有应用程序启动的global.asax中,我们有:
...
protected void Application_Start() {
ISessionFactory sf =
DataRepository
.CreateSessionFactory(
ConfigurationManager
.ConnectionStrings["conn_string"]
.ConnectionString
);
//use windsor castle to inject the session
ControllerBuilder
.Current
.SetControllerFactory(new WindsorControllerFactory(sf));
}
...
我们的DataRepository我们有: 注意:(它不是存储库 - 我的设计错误:错误的名称 - ,它更像你的NHibernateHelper,我想它更像是某种NH配置包装......)
....
public static ISessionFactory CreateSessionFactory(string connectionString) {
if (_sessionFactory == null){
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration ...
...
//custom configuration settings
...
cfg.SetListener(ListenerType.PostInsert, new AuditListener());
})
.BuildSessionFactory();
}
return _sessionFactory;
}
....
会话工厂的事情是,您不希望在每个请求上生成/构建一个。 DataRepository充当单例,确保会话工厂仅创建一次,并且在应用程序启动时。在我们的基本控制器中,我们将会话或sessionfactory注入我们的控制器(某些控制器不需要数据库连接,因此它们来自“无数据库”基本控制器),使用WindosrCastle。我们的WindsorControllerFactory:
...
//constructor
public WindsorControllerFactory(ISessessionFactory) {
Initialize();
// Set the session Factory for NHibernate
_container.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(
() => sessionFactory)
.LifeStyle
.Transient
);
}
private void Initialize() {
_container = new WindsorContainer(
new XmlInterpreter(
new ConfigResource("castle")
)
);
_container.AddFacility<FactorySupportFacility>();
// Also register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (var t in controllerTypes) {
_container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);
}
}
....
通过这个设置,每个请求都会生成一个NHibernate会话,并且通过我们的设计,我们也可以拥有不生成会话的控制器。目前这对我们来说是如何运作的。
我还可以说,在尝试配置或调试我们遇到的问题时,我发现NHProf非常有用。
答案 2 :(得分:-1)