“永久性”的SessionFactory,ASP.NET MVC和NHibernate [英] The 'Permanent' SessionFactory, ASP.NET MVC and nHibernate
问题描述
我一直在建立一个应用程序与功能NHibernate / ASP.NET MVC - 和我周围挖想通了,它被认为最适当的做法,以保持一个永久性的SessionFactory打开,然后使用会话为每个请求到数据库中。好吧,这听起来不错...
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...
我是如何做到这一点相当混乱,虽然。一切,我觉得假设一个完整的框架结构,使用某种IoC容器系统...,这对我有什么迄今为止太先进。是否有更简单的如何实现这种设计的例子吗?
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?
我已经采取了看<一个href=\"http://stackoverflow.com/questions/563030/where-can-i-find-a-good-nhibernate-and-asp-net-mvc-reference-application\">Where我能找到一个很好的NHibernate和ASP.NET MVC参考应用
即使读的书ASP.NET MVC在行动,但它的例子只是远远大于我所试图实现更加复杂。我想一个单身模式将在的的Global.asax
'的工作的Application_Start但没有取得我所希望的结果。这样可以保证我厂处置,从来没有重新创建它。
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.
推荐答案
您可以暴露 ISessionFactory
为单:
public sealed class FactoryManager
{
private static readonly ISessionFactory _instance = CreateSessionFactory();
static FactoryManager()
{ }
public static ISessionFactory Instance
{
get { return _instance; }
}
private static ISessionFactory CreateSessionFactory()
{
// TODO: configure fluentnhibernate and create a session factory
}
}
现在,你可以在你的code使用 FactoryManager.Instance
:
Now you could use FactoryManager.Instance
in your code:
using (var session = FactoryManager.Instance.OpenSession())
using (var tx = session.BeginTransaction())
{
// TODO: use the session here
tx.Commit();
}
这篇关于“永久性”的SessionFactory,ASP.NET MVC和NHibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!