gpt4 book ai didi

c# - ASP.NET MVC 中的 NHibernate 上下文 session

转载 作者:太空狗 更新时间:2023-10-29 21:59:35 25 4
gpt4 key购买 nike

我想在我的 ASP.NET MVC 2 应用程序中使用 NHibernate 的上下文 session ,但我很难找到有关如何正确执行此操作的指导。

我对每个请求的 session 感兴趣。

最佳答案

如果我这样做是对的,请告诉我。这是我想出的:

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>()));
}
}

关于c# - ASP.NET MVC 中的 NHibernate 上下文 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3679813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com