如何使用 Autofac 使用方法连接事件?

编程入门 行业动态 更新时间:2024-10-27 22:29:06
本文介绍了如何使用 Autofac 使用方法连接事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以通过接口/类(通过构造函数和属性注入)将事件连接到 Autofac 的方法而不是整个对象.我想在函数级别而不是类型级别进行绑定.我希望以编程方式完成以下工作(在 C# 中):

Is it possible to wire events to methods with Autofac instead of whole object via interfaces/classes (through constructor and property injection). I want to bind at function level instead of type level. Programmatically I expect the following job to be done (in C#):

someType.Output += someOtherType.Input;

例如 Spring 确实支持以下构造来实现:

For example Spring does support the following construct to achieve that:

<object id="SomeType" type="Whatever.SomeType, Whatever" /> <object id="SomeOtherType" type="Whatever.SomeOtherType, Whatever"> <listener event="Output" method="Input"> <ref object="SomeType" /> </listener> </object>

Autofac 是否能够做到这一点,以及如何做到这一点?是否可以将 xml 配置用于此类任务?

Is Autofac able to do that and how? Is it possible to use xml config for such a task?

推荐答案

我假设你的对象没有直接的依赖关系,比如:

I assume that you objects have no direct dependency together, like :

public class SomeType { public event EventHandler Input; public void Raise() { if (Input != null) { Input(this, new EventArgs()); } } } public class SomeOtherType { public void Output(object source, EventArgs handler) { Console.WriteLine("Handled"); } }

您可以使用 Activated 或绑定委托:

You can either use Activated or bind a delegate:

已激活:

ContainerBuilder cb = new ContainerBuilder(); cb.RegisterType<SomeOtherType>(); cb.RegisterType<SomeType>() .OnActivated(act => { var other = act.Context.Resolve<SomeOtherType>(); act.Instance.Input += other.Output; }); var container = cb.Build(); var obj2 = container.Resolve<SomeType>(); obj2.Raise();

委托版本,将注册替换为:

Delegate version, replace registration by:

cb.Register(ctx => { var other = ctx.Resolve<SomeOtherType>(); var obj = new SomeType(); obj.Input += other.Output; return obj; }).As<SomeType>();

附带说明一下,进行这种类型的绑定有时会有点危险(因为您创建了事件依赖项)并造成内存泄漏.

As a side note, doing this type of binding can sometimes be a bit dangerous (as you create an event dependency) and create memory leak.

创建一个小类来附加两个元素并实现 IDisposable 以在不再需要时取消注册事件可能是一个明智的选择.

Creating a small class that attach both elements and implement IDisposable to unregister event when not needed anymore could be a sensible option.

我认为不可能通过 xml 配置连接事件,对于这种类型的绑定,我更喜欢代码提供的编译时安全性,但也许您有 xml 的用例.

I don't think it is possible to wire events via xml configuration, and for this type of binding I would largely prefer the compile time safety offered by code, but maybe you have a use case for xml.

更多推荐

如何使用 Autofac 使用方法连接事件?

本文发布于:2023-11-05 21:13:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   使用方法   事件   Autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!