如何使用 Unity 将事件处理程序注入到事件中
如何将事件处理程序注入(附加)到 Unity IoC 容器创建的实例的 .net 事件?
示例:我有一个通过标准 .net 事件报告错误的类:
class CameraObserver
{
public event Action<Exception> UnhandledException;
[...]
}
我有另一个类负责处理这些事件:
class CrashMonitor
{
public static void HandleException(Exception x)
{ ... }
}
我想要做的是将 CrashMonitor 中的处理程序自动注入到 CameraObserver 的每个实例中,如下所示这个伪代码:
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
有没有办法用 Unity 来做到这一点?我可以想到一个丑陋的解决方法,例如从 CameraObserver 派生,并使用特殊的构造函数进行依赖注入或方法注入。但这会使系统变得更加复杂(因为你必须编写代码)。我天真地期望您可以在事件上添加 [Dependency] 属性,并且一切都应该正常。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上的统一讨论组中提出了同样的问题
我在 codeplex http://unity .codeplex.com/Thread/View.aspx?ThreadId=80728
答案是“什么都没有”。有一个 EventBroker 的演示,但它的作用更复杂(自动装配发布者和订阅者)。我仍然认为KISS机制注入事件很有用,并开始自己做。
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.