tags:

views:

29

answers:

4

I've been successfully using MEF to obtain exported class instances. However, I came across a situation where I need to enumerate a set of exported derived classes without instantiating them. I've looked up CompositionContainer's documentation and it only seems to be able to return object instances.

I know I could have a static Type field in each derived class and export it, or do my own reflection, but I'd like to know if there's a build-in way to mark classes with the [Export] attribute and then enumerate their System.Type.

+1  A: 

Is there anything wrong with using Reflection for this?

If no, that's my answer :)

Edit:

There is no builtin way to get all the types in an assembly with a certain attribute.

leppie
No, there's nothing "wrong" with using reflection for this, but as discovering [Export]'ed types is an important part of MEF, I thought it would offer support for obtaining that information.
Trillian
+1  A: 

As leppie said, there's no built in way to do this. This is by design. There's not necessarily a one-to-one mapping between exports and types (any number of parts could have property exports of type String, for example). Also, with different programming models, the part may have come from a configuration file or a dynamic programming language, so trying to get the CLR type associated with it might not make much sense.

Daniel Plaisted
That's pretty much the conclusion I had come to. Thanks.
Trillian
+1  A: 

Depending on the scope of what you are trying to do you could potentially also use System.ComponentModel.Composition.ReflectionModel.ReflectionModelServices which were API's introduced to support caching of the default catalogs. Assuming you are using the standard attributed programming model and you know all your [Export]'s are at the type level (i.e. they aren't on members) then you can call GetPartType(part) on each part in your catalog to get the type.

As Daniel pointed out if you are using other programming models then this will not work for you but if you are using only the default catalogs that come with MEF then it should do the job.

Wes Haggard
A: 

Typically you don't really need to select an export based on type. Instead, you can find the "correct" export based on metadata.

Have a look at the MEF programming guide section on Exports and metadata.

Wim Coenen