tags:

views:

502

answers:

2

I have a export defined as as follows in MEF preview 5

[ExportMetadata("Application", "CheckFolderApplication")]
[Export(typeof(ExtendedArtifactBase))]
public class CheckFolderArtifact2 : ExtendedArtifactBase
{ ...

Then I only want those imports with the "Application" "CheckFolderApplication" metadata. To currenly do that I read all the imports and then filter the result.

[Import(typeof(ExtendedApplicationBase))]
private ExportCollection<IApplication> _applications { get; set; }

public IApplication GetApplication(string applicationName)
{
    return _applications.Single(a => a.GetExportedObject().Name == applicationName).GetExportedObject();
 }

This feels really inefficient. What if I have thousands of plug-ins - do I have to read them all via MEF to just get one with the right metadata? If so how do you cache the result?

+2  A: 

Yes, in this case you will have to do the filtering yourself.

To cache the result, you can just store it in another private variable. If you want to support recomposition (you'd have to set the AllowRecomposition property of the import attribute to true), then you can implement IPartImportsSatisfiedNotification on your class and the interface's OnImportsSatisfied method will be called whenever the imports have been set.

Daniel Plaisted
Thanks Daniel, it's a ASP.NET MVC web app som I have to find out another way to cache it ...
Riri
Is this situation changed at all in .Net 4.0 or is it still the same?
Tim Lovell-Smith
@Tim It's still the same in .Net 4.
Daniel Plaisted
A: 

I found myself wanting to do something similar. I eventually imported Lazy and filtering on the metadata, as hopefully a way of avoiding instantiating the actual objects ahead of time.

[ImportMany(typeof(MyInterface))]
List<Lazy<MyInterface,MyMetadataType>> MyGuys { get; set; }

(And with strong typed metadata - I also used the feature where you can create an interface MyMetadataType with read only gets, and pass that instead of setting TMetadata = IDictionary)

I imagine MEF still has to read at least the metadata of all 'thousand plugins' though...

Tim Lovell-Smith