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:
using Castle.ActiveRecord.Attributes;
using NHibernate.Event;
[assembly: AddEventListener(typeof(MyNameSpace.MyPostLoadEventListener))]
namespace MyNameSpace
{
public class MyPostLoadEventListener : IPostLoadEventListener
{
public void OnPostLoad(PostLoadEvent @event)
{
//do what ever you want with @event.
}
}
}