A Peek into The Managed Extensibility Framework (MEF) in .NET Framework 4.0

Introduction to MEF

In this article I will be writing about Managed Extensibility Framework (MEF) along with a demo application using Windows Presentation Foundation (WPF).

Have you ever thought of building an applications by considering the extensibility of the application? I suppose most answers would be 'no'. Is this because it was not possible? No, it was so difficult. The way to load the modules dynamically (without adding a strong assembly reference to project) and plug it onto your application was through Reflection, else the other normal way is to perform code changes in order to accommodate the new modules. This is what led to the introduction of the MEF.

MEF is used to add up new modules to the application without doing any codes changes or doing a re-deployment. This has made the development of extensible applications so easy.

Component and classes for MEF in the .NET framework 4.0

The good news for .NET developers is that MEF is integrated and comes out of the box with .NET framework 4.0. The library for MEF is System.ComponentModel.Composition. All the MEF members are bundled up into the System.ComponentModel.Composition library which has to be referred explicitly to the project in order to use MEF. Below are the members of the MEF

1.Import

Attribute to decorate the element to which the modules object to be injected. It is also called the Composable Part.

1.Export

Attribute to decorate the member of the module (called as a part) which has to be exported to the main application.

1.Catalog

Catalog provides the capability for MEF to locate the exported assemblies or modules.

A few of the available catalogs in MEF are

a) AssemblyCatalog

It picks the provided assembly to pick the exported parts.

b) DirectoryCatalog

It picks the exported modules from the assemblies in the specified directory.

c) AggregateCatalog

AggregateCatalog can be used when multiple catalogs have to be considered for picking up the exported parts.

1.Composition Batch

It represents the set of Composable Parts to add and remove from the composition container.

1.Composition Container

This is the actual match making class which composes and couples the export part and composes the import part.

Fig 1.0 shows the block diagram for MEF


Fig 1.0



A Peek into The Managed Extensibility Framework (MEF) in .NET Framework 4.0

Demo for MEF using Windows Presentation Foundation (WPF)

Now let us go ahead and create a demo WPF application to add user controls from different WPF user control libraries each onto different tabs of a tab control in the main window of a WPF application.

1.Create a solution called WPFDemo

2. Add a WPF application, drag and drop a Tab control to the MainWindow.xaml

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="MainWindow" Height="350" Width="525">

1.Add a WpfUserControlLibrary project, add a Wpfuser control and name it as BlackNoteControl. Add a textbox to the user control and set the background to black.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

mc:Ignorable="d">

1. Add another WpfUserControlLibrary project, add a Wpfuser control and name it as GreenNoteControl. Add a textbox to the user control and set the background to green.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

mc:Ignorable="d">

Fig 2.0 shows the solution explorer of the project which we have created.

[explorer2.jpg]
Fig 2.0

Now in the main application we need to add the user controls to the tab control on the MainWindow.xaml.

Now our task will be to add the user controls from the two user control libraries each onto a different tab item on the MainWindow.xaml. Let us see how this can be achieved both the usual way and the MEF way.

Classic Way

In the main WPF application add strong references to the two user control libraries. Below the is the code for the MainWindow.xaml.cs

namespace MEFDemo

{

///

/// Interaction logic for MainWindow.xaml

///

public partial class MainWindow : Window

{

TabItem _tabItem;


public MainWindow()

{


InitializeComponent();

//Add the items in the constructor using the below method

ComposeControls();

}


private void ComposeControls()

{

//Create the instance of the BlackNoteControl & GreenNoteControl

BlackNoteControl blackNoteControl = new BlackNoteControl();

GreenNoteControl greenNoteControl = new GreenNoteControl();

//Add the control to a new tab item

_tabItem = new TabItem();

_tabItem.Content = blackNoteControl;

_tabItem.Header = "Tab1";

//Add it to the tab control

tabControl1.Items.Add(_tabItem);

//Add the control to a new tab item

_tabItem = new TabItem();

_tabItem.Content = greenNoteControl;

_tabItem.Header = "Tab2";

//Add it to the tab control

tabControl1.Items.Add(_tabItem);


}

}

}

As you can see the main disadvantage is that it is not an extensible solution. That is when you want to accommodate a new user control onto a new tab you have to add the reference to that library and then modify the ComposeControls method to add the new control.



A Peek into The Managed Extensibility Framework (MEF) in .NET Framework 4.0

MEF Way

First you need to add the export attribute to the user controls which has to be exported as shown below.

namespace WpfControlLibrary1

{

///

/// Interaction logic for BlackNoteControl.xaml

///

[Export(typeof(UserControl))]

public partial class BlackNoteControl : UserControl

{

public BlackNoteControl()

{

InitializeComponent();

}

}

}


namespace WpfControlLibrary2

{

///

/// Interaction logic for GeenNoteControl.xaml

///

[Export(typeof(UserControl))]

public partial class GreenNoteControl : UserControl

{

public GreenNoteControl()

{

InitializeComponent();

}

}

}


Below is the code for the MainWindow.xaml.cs to load the controls using MEF.

namespace MEFDemo

{

///

/// Interaction logic for MainWindow.xaml

///

public partial class MainWindow : Window

{

[ImportMany]

public IEnumerable NoteControls { get; set; }


public MainWindow()

{


InitializeComponent();

//Add the items in the constructor using the below method

ComposeParts();

}


private void ComposeParts()

{

//Provide the catalog path as the current executing path

var catalog = new DirectoryCatalog(".");

var container = new CompositionContainer(catalog);


var compositionBatch = new CompositionBatch();

compositionBatch.AddPart(this);

//Compose the parts.

//This will inject the user control instances onto the ImportMany atrributed

//NoteControls IEnumerable property

container.Compose(compositionBatch);


//Add the objects in the NoteControls IEnumerable property to the TabControl

for (int i = 0; i < NoteControls.Count(); i++)

{

TabItem item = new TabItem();

item.Header = string.Format("Tab{0}", i + 1);

item.Content = NoteControls.ToArray().GetValue(i);

tabControl1.Items.Add(item);

}

}

}

}

What you should note here is, you don't have to add strong references to the two user control libraries. All you need to do is just copy the libraries to the bindebug of the WPF application as shown in Fig 3.0. In future if you want to accommodate more controls, simply copy them to the bindebug folder as well and make sure that the control is decorated with the Export attribute.

[attribute3.jpg]
Fig 3.0

Fig 3.1 and 3.2 shows the output

[window4.jpg]
Fig 3.1

[window5.jpg]
Fig 3.2

Conclusion

I hope this article explained the usability of MEF and showed you how to build extensible applications. I have also attached the Demo solution along with this article.

See you in the next article!

Related Articles





About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • A modern mobile IT strategy is no longer an option, it is an absolute business necessity. Today's most productive employees are not tied to a desk, an office, or a location. They are mobile. And your company's IT strategy has to be ready to support them with easy, reliable, 24/7 access to the business information they need, from anywhere in the world, across a broad range of communication devices. Here's how some of the nation's most progressive corporations are meeting the many needs of their mobile workers …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds