我想在我的ASP.NET MVC 2应用程序中使用NHibernate的上下文会话,但我很难找到如何正确执行此操作的指导。ASP.NET MVC中的NHibernate上下文会话
我对每个请求的Session有兴趣。
我想在我的ASP.NET MVC 2应用程序中使用NHibernate的上下文会话,但我很难找到如何正确执行此操作的指导。ASP.NET MVC中的NHibernate上下文会话
我对每个请求的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>()));
}
}
很干净的例子+1 – 2014-09-25 19:01:31
我们的做法与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充当单例,确保会话工厂只创建一次,并且在应用程序启动时。在我们的基础控制器中,我们使用WindosrCastle将会话或sessionfactory注入到控制器(某些控制器不需要数据库连接,因此它们来自“无数据库”基本控制器)。我们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在尝试配置或调试我们遇到的问题时非常有用。
我没有注意到你需要ICurrentSessionContext,认为任何“每个请求的会话”都可以。 – queen3 2010-09-09 20:46:12