Freigeben über


MEF Gems–1 of many: Import vs ImportMany

Phew! We’ve been working hard! I’m planning to put another Codeplex drop soon so you can see and test the changes, and of course, share your feedback. Also looking forward to run a usability test – let me know if you’re in seattle/redmond area and if you’re willing to participate! Winking smile

If you’ve been using MEF for a while you have stumbled upon [ImportMany] and are probably using it often. What you probably don’t know is the complete story on how MEF handles collections.

What’s the difference between Import and ImportMany?

Underneath, MEF translates everything into ImportDefinition and ExportDefinition. ImportDefinition carries a cardinality: “zero or one”, “exactly one” or “zero or more”. When using the Import attribute you can either define zero or one or exactly one, which leaves one out.

Consider the following:

 [Export] Plane : ITransportSystem

[Export] Car : ITransportSystem

[ImportMany] IEnumerable<ITransportSystem>

You can safely guess what you will get, right?

 

The following is also interesting:

 [Export] IEnumerable<ITransportSystem>

[Import] IEnumerable<ITransportSystem>

Some people ask for an aggregation:

 [Export] Plane : ITransportSystem

[Export] Car : ITransportSystem

[ExportMany] IEnumerable<ITransportSystem>

// (Plane + Car + AllItems from previous one)
[ImportMany] IEnumerable<ITransportSystem> 

But we don’t support this one…

So ImportMany is a way to express that you want to import all “items” into a type capable of exposing many items (usually IEnumerable).. Next one I’ll explain more about this purposely vague last statement Smile