如何使用 ImportMany 属性定义订单?
我刚刚进入 MEF,想知道如何定义使用 [ImportMany] 导出的集合的顺序?
我在这里的意思是,如果我有两个实现接口 IService 的类(Class1、Class2),并且每个实现都位于两个不同的库中(尽管它们可能位于同一个库中),我希望在IEnumerable 集合中的 Class1 实例由 ImportMany 属性定义。因此,它就像一个功能管道,其中 Class2 调用在 Class1 调用之前进行。
另外,我在另一个库中有另一个类(Class3,它也实现了 IService),我想稍后介绍它(即一些日志记录实用程序),如何使其成为 ImportMany 集合中的第三个实例?
I am just getting into MEF and was wondering how you could define the order of collection exported with [ImportMany]?
What I mean here is if I had two classes (Class1, Class2) that implement the interface IService and each of the implementations are in two different libraries (although they could be in the same), I want the Class2 instance to be created before the Class1 instance in the IEnumerable collection defined by the ImportMany attribute. So it is like a pipeline of functionality where Class2 calls are made before Class1 calls.
Also, I have an another Class (Class3 which also implements IService) in another library, which I want introduced later on (i.e. some logging utility), how do I make this the 3rd instance in the ImportMany collection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 MEF 的角度来看,我认为您从错误的角度解决了这个问题。 MEF 鼓励接口和实现之间的分离。为了让消费者决定实现的顺序,它迫使消费者理解实现。
Visual Studio 采取的方法有点不同。它使用 OrderAttribute,通常组合使用使用 NameAttribute 让实现者指定一个订单。然后,使用者可以使用名称和顺序的组合对 ImportMany 的实现者进行排序,而无需了解底层实现。
From a MEF perspective I think you're approaching this problem from the wrong angle. MEF encourages a separation between interface and implementation. To have the consumer dictate the order of the implementations, it forces it to understand the implementation.
The approach taken by Visual Studio is a bit different. It uses the OrderAttribute, usually in combination with the NameAttribute to let the implementors specify an order. The consumer can then sort the implementors of an
ImportMany
using a combination of names and order without understanding the underlying implementation.您可以先“延迟”加载它们,然后在将它们添加到集合中时检查订单属性。
或者查看这个答案有一个例子说明了你正在尝试做的事情。
You'll could 'Lazy' load them first and then check an order attribute as you add them to a collection.
Or check out this answer which has an example of exacly what you're trying to do.