Allow Recomposition in MEF

MEF supports an opt-in feature that allows recomposition of the Import when the underlying object is changed either explicitely by the user or in the Catalog.  The Recomposable Import unit is called live import as it automatically changes the object cycle when actual underlying object is changed. Today I will discuss how exactly this works in MEF and how to use the same in your plugin based application.

[ImportMany(AllowRecomposition=true)]
public IEnumerable> GetNames { get; set; }

Here in the import, we have specified AllowRecomposition = true, that means the entire object will be recreated when the underlying collection is modified or some new object comes in to the catalog.

The Recomposable Import is not only useful in Collections, you can also use this trick for single Imports too.

For your Recomposable Import defination, when your catalog changes or rather say you put a new dll in the DirectoryCatalog, the whole collection will automatically recreated for you.

DirectoryCatalog dcatalog = new DirectoryCatalog("plugins", "*.dll");
dcatalog.Refresh();

Say your DirectoryCatalog is pointing to plugins, and before Refresh say we place a new plugin to it, the whole IEnumerable will automatically been recreated by MEF.

I hope this post comes handy.

Read more about it from the links :

Managed Extensibility Framework – A Look

Steps to write a plugin based application with MEF

Thank you for reading.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434