In my Castle ActiveRecord based application I have a base class named ARSuperClass that all my domain entities except than EntityLogger inherit from it instead of inheriting from ActiveRecordBase. I have ModifyDate and CreateDate fields in ARSuperClass that must be updated each time an entity is created or updated. Additionally each creation/updating operations must be logged in EntityLogger too.
In first solution I overrode OnSave and OnUpdate then changed ModifyDate and CreateDate in them and also added a new record to EntityLogger. This solution was working but with each entity update, two updates were occurring. It was because with changing audit fields, the object went dirty again and so another update was needed.
In second solution I replaced OnSave with BeforeSave and replace OnUpdate with OnFlushDirty. This solved duplicate updates with entity creation but entity updates were still generating two updates.
In third solution I searched for something like BeforeUpdate but Castle ActiveRecord didn’t have such a thing. So I used NHibernate’s IPreUpdateEventListener and all my problems get solved.
For more info about how to use NHibernate event listener in Castle ActiveRecord go here.
Castle ActiveRecord is a thin layer over NHibernate and provides easy and fast use of NHibernate. Regarding data save/retrieve in Castle ActiveRecord, there is some useful events like OnSave and OnUpdate that can be utilized to automate features like automatic data tracing or data auditing. Unfortunately there is situations that we need events that are not supported directly in Castle ActiveRecord. For example we need an event like AfterLoad or PostLoad in order to do some specific operations in our application. But Castle ActiveRecord didn’t provide us with such an event. Googling showed me that I can leverage NHibernate events to achieve this goal. But how can I catch firing of NHibernate’s events in Castle ActiveRecord? This was not an easy question to be googled. BTW asking in StackOverflow and some extra googling here and here showed me the way.
Listening to NHibernate events in Castle ActiveRecord was very easier than I thought. All you must do is creating a class that implements a special interface and add a special attribute in class file. That’s it. You are done! No need to modify web.config or add code when initializing Castle ActiveRecord. So here is my listener class:
public class MyPostLoadEventListener : IPostLoadEventListener
public void OnPostLoad(PostLoadEvent @event)
//do what ever you want with @event.