65.9K
CodeProject is changing. Read more.
Home

MEF organization

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (5 votes)

May 27, 2013

CPOL

1 min read

viewsIcon

15433

Setting up MEF to load plugins from a directory

Introduction

There are tons of articles about MEF, yet it was hard to grasp the relationship between cogs in its machine. Even MSDN prefers to show some code instead of describing parts a bit. Here’s how I understand the organization of MEF pieces.

The Big Picture

  • AggregateCatalog is a collection of ‘Catalogs’, each indicating how/where MEF finds plugins. There are more catalogs than those I draw here.
  • CompositionBatch is a collection of ‘Parts’ each indicating what it exports or imports (of our plugin contract) and how it does it. There are different types of 'export' and 'import' like ImportMany or Lazy import very well described by MSDN already.
  • Container uses the ‘AggregateCatalog’ to find plugins that have any of the specified ‘parts’ of the ‘Batch’.

Code

In the below C# code, PluginManager is the only ‘part’ in which I want to ‘Import’ any available instances of IMyContract and I want MEF to search for me the directory “D:\MyAppDir\Plugins\” on my hard disk.

public class PluginManager
{
    [ImportMany]
    private List<IMyContract> _plugins;

    public void Setup()
    {
        _plugins = new List<IMyContract>();

        var aggregate = new System.ComponentModel.Composition.Hosting.AggregateCatalog();

        aggregate.Catalogs.Add(new System.ComponentModel.Composition.Hosting.DirectoryCatalog(
            @" D:\MyAppDir\Plugins\"));

        var parts = new System.ComponentModel.Composition.Hosting.CompositionBatch();
        parts.AddPart(this);

        var container = 
        new System.ComponentModel.Composition.Hosting.CompositionContainer(aggregate);
        container.Compose(parts);
    }
}

Now we can access our methods inside plugins like this: _plugins[0].Method1(); considering that at least one plugin is being found and loaded by MEF.

Code of the export side (my plugin) is a class (inside a separate assembly) which looks like this:

[Export(typeof(IMyContract))]
public class MyPlugin : IMyContract
{
    public string Name { get; set; }
}

It seems that not all types of classes can be a Part class. I tried it with a class derived from another class and parts.AddPart failed.

The only needed reference is to System.ComponentModel.Composition and MEF is now part of the .NET Framework, so nothing else is needed to be installed for MEF to work correctly on destination.

History

  • 27th May, 2013: Initial version