In my previous post (here) I showed you how to setup and get running with MEF. However, what I left out from that post is how to setup MEF to allow ‘recomposition’, which is the fancy way of saying to allow your application to discover new plugins at run time. Allowing your application to discover new plugins while still running could be a major feature as it could allow you to add/change the behavior without the need to restart. One useful scenario for this could be adding a new rules for a rules engine on the fly.
Goal of this demo?
Show you how you can add in the ability to rediscover exports at runtime with MEF.
What is needed?
If you have not already done so head out to http://mef.codeplex.com/ and grab the latest source download. More than likely you will need to download and compile all the source in order to get working binaries (hey, it is a preview after all). Once you have compiled the source you need to grab the output from the ComponentModel project (assembly name is System.ComponentModel.Composition) and include this into your project.
Also, if you have not taken a look at my previous post (here) please do so now as I will be building upon that post.
Putting it together?
Configuring your imports to allow recomposition.
This is one of the great parts of MEF, performing this configuration is CAKE, all you need to do is modify the attribute you have place on your collection as follows
[ImportMany(typeof(IRule), AllowRecomposition = true)]
internal IList _rules { get; set; }
After you have added the ‘AllowRecomposition’ attribute you are pretty much done. However, if you would like to be notified (via an event) each time recomposition happens you can do as follows
public void Init()
{
try
{
var catalog = new AggregateCatalog();
var container = new CompositionContainer( catalog );
var batch = new CompositionBatch();
batch.AddPart( this );
catalog.Catalogs.Add( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );
// this is the new part
catalog.Changed += catalog_Changed;
container.Compose( batch );
}
catch ( CompositionException compositionException )
{
// testing
throw;
}
}
void catalog_Changed( object sender, ComposablePartCatalogChangeEventArgs e )
{
// do something here
var x = "";
}
Wrapping it up
As you can see, setting up MEF for recompisition is cake and is really only requires a modification to one line of code.
Till next time,
Posted
11-16-2009 5:05 AM
by
Derik Whittaker