I'm trying to add an implementation of IPostLoadEventListener to my NHibernate configuration using FluentNHibernate. I can do so as illustrated here:
how to add event listener via fluent nhibernate?
However, creating a new array to replace the old one completely discards any existing event listeners. I can get around that like so:
return Fluently.Configure()
.Database(config)
.Mappings(m => m.AutoMappings.Add(mappings))
.ExposeConfiguration(cfg =>
{
cfg.EventListeners.PostLoadEventListeners =
new IPostLoadEventListener[] {
new UtcDateEventListener(),
new DefaultPostLoadEventListener() // <<< this one is the default
};
cfg.EventListeners.SaveOrUpdateEventListeners =
new ISaveOrUpdateEventListener[] {
new UtcDateEventListener(),
new DefaultSaveOrUpdateEventListener() // <<< this one is the default
};
})
.BuildConfiguration()
.BuildSessionFactory();
But I only know about the default event listeners by stepping through the code to determine what I was overwriting. I'd like to add my event listener without overwriting any existing event listeners, but doing so like I've shown above seems very smelly, to me. The existing event listeners are exposed as an array (rather than a collection or a list, which would make more sense). Is there a cleaner way to handle this?
Do you mean something like this:
using System.Linq;
...
var list = cfg.EventListeners.PostLoadEventListeners.ToList();
list.Add(new MyPostLoadEventListener());
cfg.EventListeners.PostLoadEventListeners = list.ToArray();
That should work :)
You could just extend the default ones...
public class UtcDatePostLoadEventListener : DefaultPostLoadEventListener
{
public override void OnPostLoad(PostLoadEvent @event)
{
base.OnPostLoad(@event);
}
}
public class UtcDateSaveOrUpdateEventListener : DefaultSaveOrUpdateEventListener
{
public override void OnSaveOrUpdate(SaveOrUpdateEvent @event)
{
base.OnSaveOrUpdate(@event);
}
}
But, I'm not sure how you are supposed to know when there is a default in place or not. For example, there is none for the PreUpdateEventListener...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With