Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

MEF organization

4.43/5 (5 votes)
28 May 2013CPOL1 min read 15.4K  
Setting up MEF to load plugins from a directory
In this quick tip, I will share my understanding of the organization of MEF pieces.

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

Image 1

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

C#
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:

C#
[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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)