Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » .NET 4.0 » .NET 4.0 MEF FAQ (Socket, Plug and extension)

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

This FAQ deep dives in to .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.

Author Rank :
Page Views : 4110
Downloads : 48
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
source code.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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

Introduction and Goal


This FAQ deep dives in to .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 by free .NET Ebook which has 400 questions and answers in WCF,WPF,WWF,Silverlight and lot more from here . View our 300 videos Design Patter, UML, Function Points, Enterprises Application Block, WCF, WPF, WWF, LINQ, SQL Server, Silverlight, .NET Project, SDLC, OOP's, .NET Best Practices,  ASP.NET 4.0 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.
 
1.jpg

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.
 
2.jpg

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 who has functionality of string message implementation can attach themself 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 as "ImportMessage" and we have attributed the same with "Import" attribute.
 
class Program
{
[Import()]
public string ImportMessage
{
set;
get;
}
}

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
{
[Export()]
string ExportMessage
{
set
{
}
get
{
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 these 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.
compositionContainer.ComposeParts(this);

// use the property
Console.WriteLine(ImportMessage);
Console.ReadLine();
}

In other words export, import and compose, Below figure summarizes the same.
 
3.jpg
"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?.
 
4.jpg
5.jpg
 

Can we connect import and export via some defined contract rather than .NET data types?


In 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.
 
[Export(typeof(ImyInterface))]
class clsMyImplementation : ImyInterface
{
public string getString()
{
return "This is my string";
}
}
class Program
{
[Import()]
public ImyInterface myInterface
{
set;
get;
}
}

This looks very much similar like 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:-
 
Requirement Solution
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 in to different formats. External vendors should be able to plug in their own export mechanism in to the application.  MEF



Below table summarizes the same in a detail manner.
 
  DI / IOC MEF
Decoupling Yes  
Extensibility   Yes
Integrate Known things Yes  
Integrate Unknown thing   Yes
Automatic discovery   Yes
Registration Yes  
Discovery   Yes
Compile time Yes  
Run time   Yes


If you have still questions post it to Glenn Block over here http://codebetter.com/blogs/glenn.block/archive/2009/08/16/should-i-use-mef-for-my-general-ioc-needs.aspx
 

Can they work hand on hand?


Let say you have an application and following is your requirement.

 
Requirement Solution
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 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. Below diagram shows how they fit in to the whole game.

The end GOAL is more important when making a choice between them.
 
6.jpg
 
Below is a nice article by Mr. Nicholas Blumhardt which shows how MEF and IOC fit in.
http://blogs.msdn.com/b/nblumhardt/archive/2009/03/16/hosting-mef-extensions-in-an-ioc-container.aspx
 

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
{
[ImportMany]
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 control with export attribute exposing "UserControl" as the type.
 
[Export(typeof(UserControl))]
public partial class SilverlightControl1 : UserControl
{
public SilverlightControl1()
{
InitializeComponent();
}
}


[Export(typeof(UserControl))]
public partial class SilverlightControl2 : UserControl
{
public SilverlightControl2()
{
InitializeComponent();
}
}

Step 3: Connect and Extend it (Compose it)
 

Use the "SatisfyImport" to compose the exports and import.
 
CompositionInitializer.SatisfyImports(this);

If you run the same you should see the composed user controls in the main Silverlight UI container as shown below.
 
7.jpg
The whole Silverlight picture looks something as shown below.
8.jpg

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 attached with this article from top of this article.. 

Reference

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Shivprasad
I am currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. You can visit about my organization at www.questpond.com and also enjoy the videos uploaded for Design patter, FPA , UML , Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Wonderful images to explain .. by Mahesh On September 3, 2010
tractor and trolly. Good one.
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.