使用 ImportMany 属性时如何要求至少导入一个部件?
默认情况下,ImportAttribute
要求只有一个部分满足属性中指定的约定。可以使用 ImportAttribute.AllowDefault
属性修改此行为。本质上,这改变了行为以允许零个或一个部分满足合同。如果没有零件,则使用该导入的默认值。
ImportManyAttribute
允许零个或多个部分来满足合同。 MEF 将使用空集合、单例集合或一组部件来满足此导入,具体取决于它找到的内容。
如何告诉 MEF 空集合无效?
我应该:
- 实现
IPartImportsSatisfiedNotification
并在集合为空时从OnImportsSatisfied
抛出异常吗? - 实现我自己的
ImportOneOrMoreAttribute
? - 使用 MEF 的一些内置功能,但我不知何故缺少?
By default the ImportAttribute
requires that exactly one part will satisfy the contract specified in the attribute. This behavior can be modified with the ImportAttribute.AllowDefault
property. Essentially this changes the behavior to allow zero or one parts to satisfy the contract. If there are no parts, the default value for that import is used instead.
ImportManyAttribute
allows zero or more parts to satisfy the contract. MEF will satisfy this import using an empty collection, or a singleton collection, or a set of parts depending on what it finds.
How do I tell MEF that the empty collection is invalid?
Should I:
- Implement
IPartImportsSatisfiedNotification
and throw an exception fromOnImportsSatisfied
if the collection is empty? - Implement my own
ImportOneOrMoreAttribute
? - Use some built in functionality of MEF that somehow I am missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,MEF 仅理解三种基数:ZeroOrOne、ExactlyOne 或 ZeroOrMore。请参阅导入基数。所以你不能在MEF属性的约束下自己表达它。我不建议在 OnImportsSatisfied 中抛出异常,因为您可能会遇到其他不可预测的问题。
恐怕您能做的最好的事情就是 ImportMany 并在您使用这些导入时的上下文中验证它。
MEF only understands three cardinalities by default: ZeroOrOne, ExactlyOne, or ZeroOrMore. See ImportCardinality. So you cannot express it yourself within the constraints of the MEF attributes. I would not suggest throwing exceptions in OnImportsSatisfied because you will likely run into other unpredictable issues.
I'm afraid the best you can do is ImportMany and verify it in the context of when you would use these imports.