Jim Counts
Jim Counts

Reputation: 12795

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 collection 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?

Upvotes: 2

Views: 123

Answers (1)

Wes Haggard
Wes Haggard

Reputation: 4364

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.

Upvotes: 4

Related Questions