views:

40

answers:

2

Hi,

Just learning nhibernate with fluent, and my session provider looks like:

 public class SessionProvider
    {

        private static ISessionFactory sessionFactory;

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    sessionFactory = Fluently.Configure()
                        .Database(MsSqlConfiguration.MsSql2005.ConnectionString( c => c.FromAppSetting("sqlserver")))
                        .Mappings( m => m.FluentMappings.AddFromAssemblyOf<UserMapping>())
                        .BuildSessionFactory();
                }

                return sessionFactory;
            }
        }

        private SessionProvider()
        { }

        public static ISession GetSession()
        {
            return SessionFactory.OpenSession();
        }
    }

Is this how I should be getting my session object? Is this the 'fastest' way to do this for a high traffic website?

A: 

The "fastest" would be to simply keep 1 session for the whole app-lifecycle, but that would also be rather stupid :P (Well, with multicore nowadays, I'm not even sure if that's the fastest).

Everything seems fine. Just remember that GetSession() opens a new session on each call. Personally, I like to keep 1 session per HttpRequest, aka.:

public static ISession GetSession()
{
    if (HttpContext.Current.Items[SESSION_KEY] == null)
    {
        HttpContext.Current.Items[SESSION_KEY] = SessionFactory.OpenSession();
    }
    return HttpContext.Current.Items[SESSION_KEY] as ISession;
}
private const string SESSION_KEY = "kahsdmiashdohbasduhfasduybadsubdsabsd";

You could also do checks on the state of your session (closed, dirty, open?), and act accordingly, instead of just the "lazy-initialization".

[EDIT] BTW, it seems like you don't want to have your class instantiated (private constructor, all static members). You should declare the class as static, e.g. public static class MyClass{} . This will make it so that the class can't contain non-static members and can't be instantiated.

cwap
A: 

As a side note here is an short post on the cost of creating a new session by one of the NHibernate devs (spoiler: It's cheap)

What is the cost of opening a session

ShaneC
but setting up the configuration is the expensive call right?
mrblah
Yup, building the factory can take several seconds.. You don't wanna do that more than once :)
cwap