NHibernate Pitfalls: Making Changes to the Configuration After the Session Factory Is Built

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

You shouldn’t be making changes to the configuration instance after the session factory is built, because it won’t know about these changes. These include:

  • Adding listeners;
  • Registering named queries;
  • Creating filters.

For example, these won’t work:

   1: Configuration cfg = new Configuration();
   2:  
   3: using (ISessionFactory sessionFactory = cfg.BuildSessionFactory())
   4: {
   5:     //adding a named query
   6:     cfg.NamedQueries["ReceivedOrders"] = new NamedQueryDefinition("from Order o where o.State = 0", true, null, 20, 0, FlushMode.Never, true, "Received orders", null);
   7:  
   8:     //creating a filter
   9:     cfg.AddFilterDefinition(new NHibernate.Engine.FilterDefinition("CurrentLanguage", "code = :code", new Dictionary<String, IType>() { { "code", NHibernateUtil.String } }, false));
  10:  
  11:     //registering a listener
  12:     cfg.EventListeners.PreDeleteEventListeners = new IPreDeleteEventListener[] { new SoftDeletableListener() }.Concat(cfg.EventListeners.PreDeleteEventListeners).ToArray();
  13: }

Of course, new session factories created after applying the changes will work as expected.

                             

No Comments