title: How to inject event handlers into events with Unity
body: <p>How can I inject (attach) event handlers to .net events of instances created by the <a href="http://www.codeplex.com/unity/" rel="noreferrer">Unity</a> IoC container?</p>
  
  <p>Example: I have a class that reports errors via a standard .net event:</p>
  
  <pre><code>class CameraObserver
  {
      public event Action&lt;Exception&gt; UnhandledException;      
      [...]
  }
  </code></pre>
  
  <p>I have another class that is reponsible for handling those events:</p>
  
  <pre><code>class CrashMonitor
  {
      public static void HandleException(Exception x)
      { ... }
  }
  </code></pre>
  
  <p>What I would like to do is to automatically inject the Handler from CrashMonitor to every instance of a CameraObserver like in this pseudocode:</p>
  
  <pre><code>UnityContainer container = new UnityContainer();
  container.RegisterInstance&lt;Action&lt;Exception&gt;&gt;(CrashMonitor.HandleException)
       .RegisterType&lt;CameraObserver&gt;(new InjectionEvent(UnhandledException));
  
  var observer = container.Resolve&lt;CameraObserver&gt;();
  // CrashMonitor.HandleException is now attached to observer.UnhandledException
  </code></pre>
  
  <p>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. </p>