tags:

views:

33

answers:

2

I'm trying to add an implementation of IPostLoadEventListener to my NHibernate configuration using FluentNHibernate. I can do so as illustrated here:

http://stackoverflow.com/questions/1433638/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?

+1  A: 

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 :)

mookid8000
A: 

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...

dotjoe
That's kind of my problem. Depending on the code I have means I'm depending on a behavior that isn't explicitly defined / linked and may change with future implementations. Also, I'm implementing the interfaces directly so that if I need additional implementations in the future, I'm not dependent on a daisy chain of inheritance.
Chris
maybe best to go mookid8000's route. I do agree there should be an Add method instead of messing with arrays. I know I use some of the Default class's methods such as `GetEntityState` so I find it easier to just extend.
dotjoe