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:
[Export(typeof(IPlugin))] public class Foo : IPlugin { ... }
In your plugin consumer, create a property to hold your plugins, and add the Import attribute:
[Import(typeof(IPlugin))] 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) { Console.WriteLine(plugin.Name); }
Download the complete source to this (really, only about 10 extra lines to glue things together) and have fun!
Remember Me
Page rendered at Thursday, March 11, 2010 12:32:17 AM (Alaskan Standard Time, UTC-09:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.