Introduction
The objective of this article is to present a new feature of .NET 4.0 which is
known as Managed Extensibility Framework.
Managed Extensibility Framework provides a way to create applications that can
be extended dynamically and those extensions can be reused among multiple
applications.
MEF allows application developers to discover and consume extensions with no
configuration required. It also lets extension developers easily encapsulate
code and avoid fragile hard dependencies.
Some details about the Managed Extensibility Framework:
- When an application needs to consume external components, MEF provides a way
to discover them implicitly.
- There is a MEF component known as ComposablePart. It has two parts
- It defines all the capabilities the composable part offers
- Import: It defines the part's dependencies to other parts
- It defines all the capabilities the composable part offers
- These ComposableParts are discoverable at runtime & these are basically the
extensions.
- An extensible application using MEF declares import that can be filled by
extension components & may also declare exports to expose services to
extensions.
- Each extension component declares an Export & may also declare Imports.
- The core of the MEF composition model is the composition container which
contains all the ComposableParts available & performs composition(connecting
imports to exports).
- The most common composition container is CompositionContainer.






- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.ComponentModel.Composition;
- namespace MyMEF {
- class Extension1 {
- [Export]
- public string Message {
- get {
- return " This is Extension 1";
- }
- }
- }
- }
Explanation of the code:
We can view this class as an extension. It has only one Export component i.e. a
string read-only property.
I have defined the get accessor of the property which returns the value "This is
Extension 1".
Step 8:
Modify the MEFMain class in the following way.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.ComponentModel.Composition;
- using System.ComponentModel.Composition.Hosting;
- using System.Reflection;
- namespace MyMEF {
- class MEFMain {
- [Import]
- public string Message { get;
- set; }
- public void HelloMEF() {
- CompositionContainer container = newCompositionContainer();
- CompositionBatch batch = newCompositionBatch();
- batch.AddPart(newExtension1());
- batch.AddPart(this);
- container.Compose(batch);
- Console.WriteLine(Message);
- Console.ReadLine();
- }
- }
- }






Diptimaya PatraPosted Aug 6, 2010, 1:25 AM
Really great article on MEF.
Mahesh ChandPosted Aug 5, 2010, 11:21 AM
Like the whole step by step tutorial. Great work Urmimala. Keep it up! Cheers!
Mike GoldPosted Aug 5, 2010, 8:32 AM
Alright Urmimala, you are on a role! Thanks for intro to MEF