NHibernate 2.0 Alpha1 was released a few days ago and the 2.0 version brings a lot of new features. There is a completly new event / listener system that can be used for all sorts of cross-cutting concerns. A basic example would be to register a save/update listener that would update some common fields (like ModifiedBy, ModifiedDate).
In order to use the event system you need to create a class that either inherits from a default nhibernate event listener or from the many event interfaces. Here is an example:
using NHibernate.Event; using NHibernate.Event.Default; public class CustomSaveEventListener : DefaultSaveEventListener { protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt) { IEntity entity = evt.Entity as IEntity; if (entity != null) ProcessEntityBeforeInsert(entity); return base.PerformSaveOrUpdate(evt); } internal virtual void ProcessEntityBeforeInsert(IEntity entity) { User user = (User) Thread.CurrentPrincipal; entity.CreatedBy = user.UserName; entity.ModifiedBy = user.UserName; entity.CreatedDate = DateTime.Now; entity.ModifiedDate = DateTime.Now; } }
The reason I inherit from the default implementation is that when you specify a listener in the configuration you will replace the default listener. I am not sure what the recommended way to this is but the way I understand it is that you can choose two ways, iether you inherit a default implementation and only specify your listener in the configuration or you just implement the event interface(ISaveOrUpdateEventListener for example) but then you also need to specify the default implementation in the configuration (in order not to loose functionality).
Here is how the configuration looks like:<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> ... <listener class="NHibTest.Listeners.CustomSaveEventListener, NHibTest" type="save" /> <listener class="NHibTest.Listeners.CustomSaveEventListener, NHibTest" type="save-update" /> </session-factory> </hibernate-configuration>
You can also place the listeners within a event xml element if you want to setup many listeners of the same type. It is also possible to do this via code like this:
Configuration cfg = new Configuration(); cfg.EventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[] {new CustomSaveEventListener() };
There are many other event types, for example Load, PreUpdate, DirtyCheck, Autoflush, PostDelete. These events could be used in interesting scenarios, for example validation and security.