Equivalent of recreating Lazy<T>.Value?

Aug 28, 2011 at 8:10 PM

Let's say I have several class exported with a contract "IDummy". Now I need to import collection of objects allowing me to create instances of classes implementing IDummy. But not directly instances of these classes and not really Lazy<IDummy>.

I need to search for a specific class implementing IDummy, basing on its metadata and create multiple instances of that class. You could think of it as forcing Lazy<IDummy> to recreate its value. Something like:

[ImportMany]
IEnumerable<IDummy> dummies;

void CheckParams(string someParams)
{
    if(someParams == "expected params")
    {
          dummies[i].GetNewInstance();
    }
}

My IDummy instances are stateful and that's why I need many instances in scope of one importing class. I'd like to leverage MEF here to have IDummies automatically composed as well.
Actually I'd like to be able to write something like this (with Export<T,TMetadata> as analogy to Lazy<T,TMetadata>, but capable of creating any number of instances (more than 1) ):

[ImportMany(typeof(IDummy))]
IEnumerable<Export<IDummy, DummyMetadata>> dummyImports;

void CheckParams(...)
{
    //browse through metadatas
    ... similar as earlier ...
    dummyImports.GetExportedValue();
    ...
}

Even simpler it'd be to just recreate the Lazy<T,TMetadata>.Value - if it was possible.

While I see I could import i.e. IDummyFactory instead of IDummy directly, I'd have to produce an IDummyFactory for each IDummy export. Is there a mechanism that could help me achieve this in a simpler way in MEF?
Am I supposed to filter loaded types in a 'traditional' way instead? Or maybe loop through available MEF exports? What is the typical solution for such a scenario?

Thanks in advance.

 

 

 

someParams
Aug 28, 2011 at 8:30 PM

It sounds like you might want to use ExportFactory<T>. It allows you to get a factory for creating T. You can also import a collection of factories with the metadata for the export by using IEnumerable<ExportFactory<T,M>>. 

In other words above you would do something like this

[ImportMany(typeof(IDummy))]
IEnumerable<ExportFactory<IDummy, DummyMetadata>> dummyImports;

For your import. The factory exposes a CreateExport method you can use to create new exports. Each export exposes a Value which you can use to get to the actual instance.

ExportFactory shipped for MEF in Silverlight 4 initially, but is also now available in MEF v2.

Aug 28, 2011 at 9:57 PM

Thank you, I was not aware of ExportFactory<>. It seems to be exactly what I need.

As far as I understand, to use it for the moment, I'm supposed to replace references to System.ComponentModel.Composition from .NET4 with System.ComponentModel.Composition.Codeplex and attach the latter to my releases.