NHibernate event listeners

懵懂的女人 提交于 2020-01-02 04:55:08

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/3926993/nhibernate-event-listeners

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!