I'm starting to use MEF to build up a plugin based application, and I'm slowly adding MEF to the mix. There is a lot of existing code that does not have any MEF DNA yet, but I still want to get that code into the new objects that are being automatically created by composition.
Let's make this concrete.
I have a list of objects that implement the IFoo interface and operate on the application model in specific but useful ways.
interface IFooCool : IFoo {}
class FooCool : IFooCool {...}
interface IFooAwesome : IFoo {}
class FooAwesome : IFooAwesome {}
IEnumerable<IFoo> fooCollection = ProvidedTheOldFashionWay(not, yet, MEF);
Now, I want to create some useful tools that map the IFooX
interfaces to various user actions like menu commands or button clicks.
[Export(ITool)]
class CoolTool : ITool
{
IFooCool _fooCool;
[ImportingConstructor]
CoolTool(IFooCool fooCool)
{
_fooCool = fooCool;
}
[Export(MenuAction)]
void DoSomething() { _fooCool.SomeWork(...); }
}
Here's what I'd like to do:
var batch = new CompositionBatch();
foreach(var foo in fooCollection)
{
batch.AddPart(foo); //add those legacy objects to the batch
}
var catalog = new TypeCatalog(typeof(CoolTool)); //or assembly or directory, ...
var container = new CompositionContainer(catalog);
container.Compose(batch);
The CoolTool
will be instantiated and the FooCool
legacy object will be passed to it. Then I can get the exported functions and display them nicely in the menu and off we go. When the user clicks a menu item, the new CoolTool
will use the existing functionality of the IFooCool
interface to do something, well, cool.
Of course, that doesn't work. Since the legacy objects are not attributed as exports, adding them to the composition batch does not help. In the code above, I'm adding the foo instances to the batch with batch.AddPart(object)
instead of batch.AddPart(ComposablePart)
. The first method uses the attributed model to discover composable information from the object.
How can I use the second overload? Can I wrap my existing non-MEF object in a ComposablePart on the fly? Something like:
batch.AddPart(CreateComposablePart(typeof(IFooCool), foo));
BTW, I'm use preview 8 in a non-silverlight app.