# Friday, April 03, 2009


For a project I'm doing, I have a task model for the various pieces. In the beginning, I was manually creating a List<ITask>. As I kept adding tasks to run, I started thinking about hacking some code together to rifle through my assembly and pull back all the classes which implement ITask.

Then I remember hearing about Managed Extensibility Framework (MEF). I did some searching, found the MEF home page, and even read the MEF overview. But none of that told me what I really wanted to know, what's the fastest way to get started using MEF as a component loader?

I did some more searching and found the dnrTV episode "Glenn Block on MEF, the Managed Extensibility Framework" and after 20-30 minutes they finally got down to how to create a plugin for your app.

But what I really wanted, and I bet a lot of others, is a quick start guide for creating a plugin.


Download the latest version of MEF, as of this writing its Preview 4. Grab the System.ComponentModel.Composition.dll from the bin folder and stash it somewhere. Make a reference to said dll in your project.

On your plugin class, add Export attribute:

public class Foo : IPlugin { ... }

In your plugin consumer, create a property to hold your plugins, and add the Import attribute:

internal IList<IPlugin> _myPlugins { get; set; }

Now, tell MEF where to get the plugins at (line 2), and where you want MEF to fulfill any plugins (line 5):

private void LoadPlugins() { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); var batch = new CompositionBatch(); batch.AddPart(this); container.Compose(batch); }


I put my call to the LoadPlugins method in the constructor.

Now, spin through your plugins and do the work:

Console.WriteLine("Found {0} plugins", _myPlugins.Count);
foreach (var plugin in _myPlugins) {


Download the complete source to this (really, only about 10 extra lines to glue things together) and have fun!

kick it on DotNetKicks.com
.NET | C# | HowTo | MEF
Friday, April 03, 2009 8:37:33 PM (Alaskan Standard Time, UTC-09:00)