EventAggregator's IHandle interface

Jul 27, 2011 at 6:08 PM


I've recently started using the EventAggregator in a web app, and I'm excited about the power that it provides when coupled with dependency injection.  It's very powerful while remaining light-weight.

One thing I've wondered about is the use of the non-generic IHandle interface.  The only reference I see to this is in the Handler class:


var interfaces = handler.GetType().GetInterfaces()
    .Where(x => typeof(IHandle).IsAssignableFrom(x) && x.IsGenericType);

foreach(var @interface in interfaces) {
    var type = @interface.GetGenericArguments()[0];
    var method = @interface.GetMethod("Handle");
    supportedHandlers[type] = method;

Would it be possible to remove the non-generic IHandle interface and replace the first line above with:

var interfaces = handler.GetType().GetInterfaces()
    .Where(x => x.IsGenericType && typeof(IHandle<>).IsAssignableFrom(x.GetGenericTypeDefinition()));


This would help prevent a misuse of the IHandle interface... a user could define a custom interface such as:

public interface IMyNewHandle<TMessage> : IHandle
    // Do not define the Handle method.

In this scenario, the EventAggregator will try to look for a "Handle" method that does not exist.  It will later throw a NullReferenceException when attempting to invoke the method.

This is definitely not a typical scenario, but I'm curious if there is another use of the non-generic IHandle interface that I'm not aware of.



Jul 27, 2011 at 9:00 PM

The non-generic IHandle makes it easy to detect classes that handle events. This is useful for IoC autowiring of event subscription. The code is greatly simplified by the presence of the non-generic interface.

Oct 31, 2011 at 9:37 PM

If you're interested in how to do the autowiring with MEF (that is; make the "eventAggregator.Subscribe(this)" happen automagically), I just did a blog post on this here; http://www.kjetilk.com/2011/10/auto-wiring-eventaggregator.html


Kjetil Klaussen