开发者

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:

  1. Implement IPartImportsSatisfiedNotification and throw an exception from OnImportsSatisfied if the collection is empty?
  2. Implement my own ImportOneOrMoreAttribute?
  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜