The 'Permanent' SessionFactory, ASP.NET MV

2019-03-21 16:11发布

问题:

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.

回答1:

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


回答2:

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.