Cobra_Fast
Cobra_Fast

Reputation: 16111

How to import only types, not instances?

I'm importing DLLs which export an IPlugin class by using MEF (System.ComponentModel.Composition) with the [ImportMany(typeof(IPlugin))] attribute.

Here's the code I use to fetch the extensions:

AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog(AppDataHelper.ExeDir + "/Module/"));
CompositionContainer container = new CompositionContainer(catalog);
CompositionBatch batch = new CompositionBatch();
batch.AddPart(this);

However, as far as I see, the corresponding property will hold instances afterwards.

How do I import only types (preferrably Type objects) of the extensions so I can create instances however I like myself?

Upvotes: 2

Views: 252

Answers (2)

BradleyDotNET
BradleyDotNET

Reputation: 61379

You can't, MEF works by creating a single instance of every compatible and exported type it finds.

The easiest way around this is to import factories and then use them to create the actual instances.

The interface would look something like:

interface IPluginFactory
{
    IPlugin CreateInstance();
    string TypeName {get;}
}

And then you search the MEF populated collection of factories for the right type name and call its CreateInstance function.

Upvotes: 4

TomTom
TomTom

Reputation: 62159

Generate a catalog, then work from there (without composition batch) and find the relevant type from there yourself.

Upvotes: 0

Related Questions