“永久” SessionFactory、ASP.NET MVC 和 nHibernate
我一直在使用 Fluent nHibernate/ASP.NET MVC 构建一个应用程序 - 我已经深入研究并发现保持“永久”SessionFactory 打开,然后对数据库的每个请求使用会话被认为是最合适的做法。好吧,这听起来不错……
不过,我对如何实现这一目标感到很困惑。我发现的所有内容都假设一个完整的结构化框架,该框架使用某种 IoC 容器系统……这对于我迄今为止所拥有的来说太先进了。有没有更简单的例子来说明如何实现这种设计?
我查看了 我在哪里可以找到一个好的NHibernate和ASP.NET MVC参考应用程序
甚至阅读了《ASP.NET MVC in Action》这本书,但它的示例比我想要实现的要复杂得多。我认为单例模型可以在“global.asax
”的 Application_Start 中工作,但这并没有产生我所希望的结果。它会继续处置我的工厂,并且永远不会重建它。
I've been building an application with Fluent nHibernate/ASP.NET MVC - and I've dug around and figured out that it's considered most appropriate practice to keep a 'permanent' SessionFactory open, and then use sessions for each request to the database. Okay, this sounds good...
I'm quite confused on how to accomplish this, though. Everything I find assumes an entire structured framework that uses some kind of IoC container system ...and that's just too advanced for what I have so far. Are there any more simple examples of how to implement this kind of design?
I've taken a look at Where can I find a good NHibernate and ASP.NET MVC Reference Application
And even read the book "ASP.NET MVC in Action", but it's example is just far more complicated than what I am trying to achieve. I thought a singleton model would work in the Application_Start of the 'global.asax
' but that didn't yield the results I had hoped for. It would keep disposing of my factory and never recreating it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
ISessionFactory
公开为单例:现在您可以在代码中使用
FactoryManager.Instance
:You could expose the
ISessionFactory
as singleton:Now you could use
FactoryManager.Instance
in your code:在全局 MvcApplication 类上创建静态 GetSessionFactory 方法。此方法在第一次调用时初始化会话工厂并将其存储为私有静态变量。在后续调用时,它仅返回静态变量。
此方法还可以检查对象是否为空或已释放,并根据需要重新创建,尽管这种情况不应该发生,因为变量将是静态的,因此在应用程序的生命周期内保持活动状态。
Make a static GetSessionFactory method on your global MvcApplication class. This method initializes a session factory the first time it is called and stores it as a private static variable. Upon subsequent calls, it simply returns the static variable.
This method can also check to see if the object is null or disposed and recreate as necessary, though it shouldn't happen since the variable would be static and thus, stay alive for the duration of the application's lifetime.