Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching Fluent NHibernate ISessionFactory

We're building a mobile application, and we're evaluating NHibernate + Fluent for use with it. The problem is, the first time we create the ISessionFactory, it takes a full 2 minutes. even though the table structure is very simple (3 tables).

each call after that is extremely fast.

what i'd like to do is either cache the ISessionFactory between application restarts, or somehow speed up the creation of it in the first place.

Any ideas on if it's possible to cache? from all my reading, there's not much speeding it up.

like image 502
bryan costanich Avatar asked Dec 14 '25 22:12

bryan costanich


2 Answers

You can serialize and save the configuration and load that up the second time around to reduce the time it takes to create. Tho if you make changes you need to blow away the old config and serialize a new version, otherwise you will be loading up old configuration.

I can't remember the code to do this tho, will try dig up an example.

Edit: http://vimeo.com/16225792

In this video at about 24 minutes in Ayende discusses Configuration Serialization.

like image 108
Phill Avatar answered Dec 16 '25 22:12

Phill


Defining your ISessionFactory as a static variable (Shared for VB) and instantiating it only once upon application startup is how web apps get around this. I realize this may pose a challenge for a mobile app with memory efficiency demands but depending on the mobile platform you're using the application lifetime may not be as short as one would fear...

    public class NHHelper {
        private static string _connectionString;
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory {
            get {
                if (_sessionFactory == null) {
                            _sessionFactory = Fluently.Configure()
                                .Database(MsSqlConfiguration.MsSql2008.ShowSql()
                                    .ConnectionString(p => p.Is(_connectionString)))
                                .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetAssembly(typeof(NHHelper))))
                                .BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

// this is called once upon application startup...
        public static void WarmUpSessionFactory(string connectionString) {
            _connectionString = connectionString;
            var factory = SessionFactory;
        }
// this is what you call to get a session for normal usage
        public static ISession OpenSession() {
            return SessionFactory.OpenSession();
        }
    }
like image 42
Tahbaza Avatar answered Dec 16 '25 21:12

Tahbaza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!