How to add event listener via Fluent NHibernate?

痴心易碎 提交于 2019-12-04 22:50:51

Late answer, found your question when I was trying to do the same. Found a solution that should work:

_sessionFactory = Fluently.Configure()
   .Database(MsSqlConfiguration.MsSql2005.ConnectionString(connectionString).ShowSql())
   .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Entity>())
   .ExposeConfiguration(c => c.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] {new AuditEventListener()});

So, late response, but for the sake of posterity, to add listeners without removing existing registration listeners (like the earlier answer from Bengt Be will do):

var config = new Configuration ();
config.AppendListeners (ListenerType.PreUpdate, new [] { new AuditEventListener () });

etc.

Resurrecting the dead here but this:

........
   .ExposeConfiguration(c => c.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] {new AuditEventListener()});

Should be:

.ExposeConfiguration(c => c.AppendListeners(ListenerType.PreUpdate, new object[]
    {
        new AuditEventListener()
    });

I believe the 'SetListener' method (described in another answer) would also remove all previous listeners.

If you are into something a little more dynamic, you could do this:

private void AddListenerToConfiguration<T>(FluentConfiguration config, params ListenerType[] typesForListener)
        where T : class
    {
        var listener = Activator.CreateInstance<T>();

        config.ExposeConfiguration(x =>
            {
                foreach (var listenerType in typesForListener)
                {
                    x.AppendListeners(listenerType, new T[]
                    {
                        listener
                    });
                }
            });
    }

And then call something like this:

AddListenerToConfiguration<AuditEventListener>(smFactory, 
            ListenerType.PreUpdate);

This allows for cleaner code while you are looking at the Fluent configuration. It also allows you to easily register a single type to multiple listener types.

As for removing the default listeners, I wouldn't remove them unless I have a listener that inherits from the default listener implementation and calls base.METHODNAME on the overridden methods or replicates the same behavior as that of the default listeners.

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