Search code examples
c#.netlistmefinstantiation

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?


Solution

  • 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.