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.