views:

115

answers:

1

How can I inject (attach) event handlers to .net events of instances created by the Unity IoC container?

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

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 syste more complex (because you have to write code). I would naively expect that you could add a [Dependency] attribute on the event and everything should work.

A: 

I have asked the same question in the unity discussion group on codeplex

http://unity.codeplex.com/Thread/View.aspx?ThreadId=80728

and the answer is "there is nothing". There is a demo of an EventBroker but what it does is more complex (autowiring of publishers and subscribers). I still think a KISS mechanism to inject events is useful and started to do it by myself.

Christian Rodemeyer