Click here to Skip to main content
14,663,611 members
Articles » Web Development » ASP.NET » General
Posted 31 Aug 2010


158 bookmarked

.NET 4.0 MEF FAQ (Socket, Plug and extension)

Rate this:
4.92 (73 votes)
Please Sign up or sign in to vote.
4.92 (73 votes)
8 Sep 2010CPOL
.NET 4.0 MEF FAQ (Socket, Plug and extension)

Video Update....

This video talks about .NET 4.0 feature called as MEF Managed extensibility framework.

Image 1

Table of Contents

Introduction and Goal

This FAQ deep dives into .NET 4.0 MEF fundamentals (Import and Export) and also explains when to use MEF over DI / IOC. This article also explains step by step on how to use MEF in various technologies like Silverlight, WPF and ASP.NET.

Please feel free to download my free .NET Ebook which has 400 questions and answers in WCF, WPF, WWF, Silverlight and lot more from here.

What is MEF (Manage Extensibility Framework)?

MEF is a framework by which you can make your application extensible. For example, you have an accounting application and you would like to provide a hook (socket) where external vendors can connect (plug) and add invoicing capabilities to the accounting application.

For instance, you have application which you would want different vendors to connect with their features and extend your application.

So the vendors just put the components in the application, the application discovers them and does the connection and extension.

Image 2

How Can We Implement MEF in .NET 4.0?

Implementing MEF is a three step process:

• Import (Create the socket): Use the “Import” attribute to define a hook or socket in your application.
• Export (Attach the Plug): Use the “Export” attribute to create the plug which can attach to the plug or hook.
• Compose (Extend it): Use the composition container and compose it.

Image 3

Can We See A Simple Example of MEF with the Above 3 Steps?

We will create a simple class which will have a hook to import string message. In other words, any class which has functionality of string message implementation can attach themselves to the hook and extend that class.

Step 1: Create the Socket (Import)

The first step is to create a place holder / hook / socket where other components can plug in.

Import the below namespaces needed by MEF.

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

To define a hook, we have created an empty property called “ImportMessage” and we have attributed the same with “Import” attribute.

class Program
public string ImportMessage

The above “import” attribute says that anyone who has string functionality implementation type can connect to me and attach the functionality.

Step 2: Create and Attach the Plug (Export)

In order to create the plug or extension, we need to use the “Export” attribute as shown below. This attribute in the current scenario does nothing but displays a simple string.

class clsMySimpleMessage
string ExportMessage
return "Message inserted via MEF";

Step 3: Connect and Extend it (Compose it)

Ok, so we have created the socket, the plug and it’s time to connect both. Below goes the code for the same:

private void Compose()
// Get a reference to the current assemblies in the project.
AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

// Once you have got the reference of catalog add it to the composition container.
CompositionContainer compositionContainer = new CompositionContainer(catalog);

// Finally call composeparts to connect the Import with Export.

// use the property

In other words export, import and compose. The below figure summarizes the same:

Image 4

Export” is like things you give off and “import” is like things which you take in.

Should Data Types of Import and Export Match?

The types of import and export should match or else while composing you will get an error as shown below. Can incompatible socket and plug connect?

Image 5

Image 6

Can We Connect Import and Export via Some Defined Contract Rather than .NET Data Types?

In the real world, your hooks would be some real world contract types like customer, supplier, etc. rather than simple .NET data types like string, int, Boolean, etc. In order to create a real word kind of hook in MEF, we need to first create a contract using interfaces as shown below:

interface ImyInterface
string getString();

We need to ensure that the hooks defined in both import and export attribute are of the same interface type as shown below. The binding logic using composition container does not change; it’s the same as described in the previous section.

class clsMyImplementation : ImyInterface
public string getString()
return "This is my string";
class Program
public ImyInterface myInterface

This Looks Very Much Similar to DI and IOC, Why the Re-invention?

In case you are new to DI/IOC, read from here.

Both of them overlap each other to a very great extent, but the GOALS are different. DI and IOC is meant for decoupling, while MEF is for extensibility. The below requirement will throw more light on how to decide which solution to go for:

The application should be a tiered application with each tier decoupled from each other for better reusability and maintainability.DI IOC
The application should provide a facility of exporting data into different formats. External vendors should be able to plug in their own export mechanism into the application.MEF

The below table summarizes the same in a detailed manner:

Integrate Known thingsYes
Integrate Unknown thingYes
Automatic discoveryYes
Compile timeYes
Run timeYes

If you have still questions, post it to Glenn Block over here.

Can They Work Hand In Hand?

Let's say you have an application and following is your requirement:

The application should be 3 tier architecture with UI, BO and DAL layer decoupled from each other.DI IOC
The data access layer needs to be open and extensible. The application will provide the ability to vendors to plug their own data connection mechanism so that application can connect to their proprietary databases.MEF

The way to approach the first requirement is by using your favorite IOC container and the second requirement is where MEF fits. The below diagram shows how they fit into the whole game.

The end GOAL is more important when making a choice between them.

Image 7

Here is a nice article by Mr. Nicholas Blumhardt which shows how MEF and IOC fit in.

We Would Like to See a Sample in Silverlight?

The main important steps do not change.

Step 1: Create the Socket (Import)

Define the Silverlight items you want to import. In the below code snippet, we have defined a collection of user control type.

public partial class MainPage : UserControl
public ObservableCollection<UserControl> ImportedItems
{ get; set; }

Step 2: Create and Attach the Plug (Export)

Use “Export” to define the plug. For the current scenario, we have defined two Silverlight user controls with export attribute exposing “UserControl” as the type.

public partial class SilverlightControl1 : UserControl
public SilverlightControl1()

public partial class SilverlightControl2 : UserControl
public SilverlightControl2()

Step 3: Connect and Extend it (Compose it)

Use the “SatisfyImport” to compose the exports and import.


If you run the same, you should see the composed user controls in the main Silverlight UI container as shown below:

Image 8

The whole Silverlight picture looks something as shown below.

Image 9

Can We Also See a Simple Sample in WPF?

Phrrr..phusss….tired will update soon.

How About Some Sample in ASP.NET?

Phrrr..phusss….tired will update soon.

Source Code

You can get the source code from the link at the top of this article.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Comments and Discussions

GeneralMy vote of 5 Pin
Savalia Manoj M25-Dec-12 17:07
MemberSavalia Manoj M25-Dec-12 17:07 
GeneralMy vote of 5 Pin
Sperneder Patrick18-Oct-12 0:32
professionalSperneder Patrick18-Oct-12 0:32 
GeneralMy vote of 5 Pin
ali_reza_zareian13-Oct-12 19:40
Memberali_reza_zareian13-Oct-12 19:40 
GeneralMy vote of 5 Pin
Ra-one23-Apr-12 0:46
MemberRa-one23-Apr-12 0:46 
GeneralMy vote of 5 Pin
mojmos20-Apr-12 19:30
Membermojmos20-Apr-12 19:30 
GeneralMy vote of 5 Pin
Adil Mughal27-Feb-12 20:36
MemberAdil Mughal27-Feb-12 20:36 
GeneralMy vote of 5 Pin
Vinod Satapara7-Feb-12 2:09
MemberVinod Satapara7-Feb-12 2:09 
GeneralMy vote of 5 Pin
Prathapachandran8-Nov-11 18:00
professionalPrathapachandran8-Nov-11 18:00 
GeneralMy vote of 5 Pin
Steve Maier27-Apr-11 9:40
professionalSteve Maier27-Apr-11 9:40 
GeneralMy vote of 5 Pin
fmsalmeida5-Apr-11 7:36
professionalfmsalmeida5-Apr-11 7:36 
GeneralMy vote of 5 Pin
Luka5-Nov-10 11:26
MemberLuka5-Nov-10 11:26 
GeneralMy vote of 5 Pin
Petr Pechovic8-Oct-10 6:12
professionalPetr Pechovic8-Oct-10 6:12 
GeneralMy vote of 5 Pin
Eric Xue (brokensnow)7-Sep-10 20:02
MemberEric Xue (brokensnow)7-Sep-10 20:02 
GeneralMy vote of 5 Pin
Abhijit Jana4-Sep-10 6:05
professionalAbhijit Jana4-Sep-10 6:05 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»4-Sep-10 0:43
professionalKunal Chowdhury «IN»4-Sep-10 0:43 
GeneralMy vote of 5 Pin
defwebserver3-Sep-10 4:09
Memberdefwebserver3-Sep-10 4:09 
GeneralSimple and brilliant Pin
Sainath Sherigar1-Sep-10 7:00
MemberSainath Sherigar1-Sep-10 7:00 
GeneralMy vote of 5 Pin
hirenkishir1-Sep-10 3:47
Memberhirenkishir1-Sep-10 3:47 
GeneralLove your articles, 5 from me Pin
Marcelo Ricardo de Oliveira1-Sep-10 3:38
mvaMarcelo Ricardo de Oliveira1-Sep-10 3:38 
GeneralPretty useful and timely Pin
Rajesh Pillai1-Sep-10 2:30
MemberRajesh Pillai1-Sep-10 2:30 
GeneralCrystal clear! Pin
Anantharaman_N1-Sep-10 2:22
MemberAnantharaman_N1-Sep-10 2:22 
GeneralGreat work Pin
Abhishek Sur31-Aug-10 22:56
professionalAbhishek Sur31-Aug-10 22:56 
GeneralMy Salute to the King - Great work and rare articles Pin
javedsid8783931-Aug-10 22:29
Memberjavedsid8783931-Aug-10 22:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.