Here I am with another post! This is supposed to be a crash course or a refresher (call it whatever you want!) on MEF (Managed Extensibility Framework).

Consider the following gist. In order to create a fairly simple yet meaningful application that demonstrates MEF, you need 3 projects within a solution. Obviously, this is not the only way, but something which I feel demonstrates MEF really well.


The first project is the MefContracts project that defines contracts or interfaces that will be “imported” or “used” by another project (starting with line 1 in the gist).

The second project is a project that provides reference implementations of the contracts (or interfaces) defined in the first step, lets call it MefLibs. Since they are implementing interfaces from MefContracts, they need a reference to that project! Any implementation that should be available for classes that “imports” a contract should have the attribute Export indicating this is available for consumption. If they do not have this attribute, even if they implement the interface, will be ignored.

The third and final project is something that actually puts MEF in to use and so is a console application. It DOES NOT need a reference to MefLib, but does need a reference to MefContracts [obviously: that's the whole point of MEF!]. Now, you will notice a number of variables decorated with Import and ImportMany attributes. This just indicates that (1) Import – if MEF finds an implementation of IGreeting, create an instance of it and assign it to this variable and (2) ImportMany – if MEF finds multiple implementations of IPlugin, instantiate an instance of each of them and assign it to this variable.

Without any other steps, if you create a solution, add these interfaces, build and run, you will just get an exception. This is because of the locations your program is looking at, refer to the Compose method. In short, its only looking the “bin” folder of your executable and the current assembly. So to get it to work, just copy “MefLib.dll” from the project’s bin folder and you will be all set!!

The following image is my attempt at simplifying various aspects of MEF. If this makes it even more confusing, feel free to ignore it :)


Published on

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

the dotNet way!

experiments w/, c#, ruby and many more!!

Back to Home