The 'Permanent' SessionFactory, ASP.NET MVC and nHibernate

不羁岁月 提交于 2019-12-03 08:56:54

You could expose the ISessionFactory as singleton:

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
    }
}

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!