MEF stands for Managed Extensibilty Framework and allows C# developers to developer plug-in architectures for their solutions.
This allows any C# project (WPF, Silverlight, ASP.NET, Winforms, Class Library, etc) to make use of external functionality dynamically at runtime without the need for a hard coded reference. This is made possible through the use of interfaces and MEF with it’s Import and Export attributes and only takes a few lines of code.
MEF is part of the .NET Framework v4.0 and is being used in future versions of Visual Studio to provide their plug-in model.
In our demo the host application, in this instance a console app, will load two plug-ins to provide CalculationServices. Both will implement a Calculate method accepting two integers and returning an integer. The first CalculationService will add the two numbers together and the second CalculationService plug-in will multiple the numbers together.
Coding the Demo
First create a Console application called MefSimpleDemo.exe then add three class libraries to the solution:
SharedContracts (for our interfaces)
The Console Application and SharedContracts projects will need to reference MEF and the our Interfaces so right clcik and add the two references for each project.
MEF is stored within the System.ComponentModel.Composition framework (System.ComponentModel.Composition.DLL).
In our example the plug-ins will be loaded from a known directory location. In production you would load this location from a config but for this demo we’ll be hardcoding the location (@”../plugins” folder) in the host and building the output of the plug-ins to the same folder. To alter the output right click on view properties on both plugins click the “Build” tab and update the “Output Path”:
SharedContracts.DLL Class Library
Remove the default Class1.cs file, add a file called ICalculationService.cs and paste in the following code:
NOTE: Notice the (MEF) InheritedExport attribute on the interface, this allows MEF to discover the class within the plugin.
CalculationService1.DLL Class Library
Remove the default Class1.cs file, add a file called Addition.cs and paste in the following code:
CalculationService2.DLL Class Library
Remove the default Class1.cs file, add a file called Multiply.cs and paste in the following code:
MefSimpleDemo.EXE Console Application
Add a new file called PluginRepository.cs and paste in the following code:
Finally replace the text in the Program.cs file with the following code:
Your solution should now look like this, notice I’ve removed all redundant references from each of the projects:
You are now ready to run the application, press F5 and check out your results:
You can download the source code here: