Is it possible to inject into events?

Jan 13, 2010 at 8:37 PM
Edited Jan 14, 2010 at 2:43 PM

Hello,

How can I inject (attach) event handlers to .net events? It seems that only property or method injection is supported, but no event injection.

Example: I have a class that reports errors via a standard .net event:

class CameraObserver
{
    public event Action<Exception> UnhandledException;     
    [...]
}

I have another class that is reponsible for handling those events:

class CrashMonitor
{
    public static void HandleException(Exception x)
    { ... }
}

What I would like to do is to automatically inject the Handler from CrashMonitor to every instance of a CameraObserver like in this pseudo code:

UnityContainer container = new UnityContainer();
container.RegisterInstance<Action<Exception>>(CrashMonitor.HandleException)
     .RegisterType<CameraObserver>(new InjectionEvent("UnhandledException"));
 
var observer = container.Resolve<CameraObserver>();
// CrashMonitor.HandleException is now attached to observer.UnhandledException

Is there a way to do this with Unity? I can think of an ugly workaround like deriving from CameraObserver with a special constructor intendend for dependency injection or or a method injection. But that would make the system more complex (because you have to write code).

Thanks,

Christian

Jan 14, 2010 at 5:40 AM

There's the EventBroker quickstart that demonstrates how you could add this capability to Unity with an extension, but it's not really production ready (hasn't been through serious testing) and it's fairly inflexible.

Autowiring events is something that's fraught with gotchas and everyone wants to do it slightly differently, so there's nothing for it in the core container.

 

Jan 14, 2010 at 2:42 PM

I think the EventBroker sample did something more complex than I need. I don't want autowiring of publishers and subscribers. I just want to register EventHandlers and then mark those events (e.g. with the [Dependency] attibute) that should get injected. For me that sounds pretty analog to what the InjectioProperty class does.

In fact I have downloaded the latest version and it seems that by doing a dumb copy & replace on InjectionProperty and related classes I am able to get what I want.