Ensure NHibernate SessionFactory is only created once?

The sessionFactory must be a thread-safe singleton.

The sessionFactory must be a thread-safe singleton. A common pattern in Java is to build the sessionFactory in a static initializer. See You can do the same in C#.

There are other patterns to implement singleton, including the usage of lock or synchronized sections. Here is slight variant that should solve your problem if I understood it correctly. Static readonly object factorylock = new object(); public ISession OpenSession() { lock (factorylock) { if (_sessionFactory == null) { var cfg = Fluently.Configure().

Database(SQLiteConfiguration.Standard.ShowSql(). UsingFile("Foo. Db")).

Mappings(m => m.FluentMappings. AddFromAssemblyOf()); _sessionFactory = cfg. BuildSessionFactory(); BuildSchema(cfg); } } return _sessionFactory.OpenSession(); }.

Thanks! Sounds reasonable. I just added a solution using Mutex.

But I should use lock instead? – stiank81 Mar 2 '10 at 10:08.

I solved this using a Mutex when creating the SessionFactory. Does this look reasonable: public class NhibernateSessionFactory : INhibernateSessionFactory { private static ISessionFactory _sessionFactory; private static Mutex _mutex = new Mutex(); // m.FluentMappings. AddFromAssemblyOf()); _sessionFactory = cfg.

BuildSessionFactory(); BuildSchema(cfg); }.

Hmm...Looks like the "double-check locking", which is not a recommended practice to implement singleton (see this page yoda.arachsys. Com/csharp/singleton. Html).

Also, a plain lock can be used instead of a mutex. – ewernli Mar 2 '10 at 10:11 Thanks! Sounds like I should go with the plain lock instead.

– stiank81 Mar 2 '10 at 10:21.

I solved this using a Mutex when creating the SessionFactory. Does this look reasonable.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions