How do I require that at least one part is imported when using the ImportMany attribute?
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 collecti开发者_开发问答on 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?
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.
精彩评论