如何使用 Unity 将事件处理程序注入到事件中

发布于 2024-08-17 08:17:34 字数 1024 浏览 4 评论 0原文

如何将事件处理程序注入(附加)到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍景流年 2024-08-24 08:17:34

上的统一讨论组中提出了同样的问题

我在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文