Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject event handlers into events with Unity

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.

like image 813
Christian Rodemeyer Avatar asked Oct 25 '22 22:10

Christian Rodemeyer


1 Answers

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.

like image 106
Christian Rodemeyer Avatar answered Dec 17 '22 23:12

Christian Rodemeyer