December 2009 - Posts
Code cartoons – MEF
The super hero agency

Why and When slides from my MEF lecture
some time we are so enthusiastic about the technology,
that we forgot to explain the Why and When.
so I thought it could be nice to share those aspects with you.
when we asking Why to use the MEF technology we can think on the following reasons:
• Simple to understand
• Simple to implement
• The CLR 4 Extensibility standard
• Contract based model (type safe)
• Easy deployment (support copy / paste deployment)
• Zero configuration
• Ease of Maintenance
• Silverlight support
rules of thumb for When should we consider using MEF.
when ever we are using or considering one of the following,
we may use MEF instead:
• Reflection
• Factory pattern
• Command pattern
• Any other creational pattern
• IoC (Inversion of control)
MEF at the SDP
today i was lecturing at the SELA SDP about building composite WPF shell application using MEF.
first I want to thanks all attendant that was there despite of the latency in the schedule.
second I want to thanks Yaniv Rodenski for his part in the lecture.
Yaniv was demonstrating real world solution that combine the
WCF power with the MEF charm :)
as I promised you can find the presentation and the code sample that I was showing
(and Yaniv was kind enough to let me publish his code as-well) ,
at the following location:
http://cid-9bf7c1a515d76a9a.skydrive.live.com/browse.aspx/Code%20Samples/MEF/SDP
if you having question, or any thing else (except junk mail and viruses of course)
you can reach me at bnayae@sela.co.il
MEF for Beginner – Part 4 (a-sync Silverlight loading)
in this post we will continue from the point that we left our Silverlight application at part 3 of this series.
the post will focus on how to consume external plug-ins using a-sync loading into Silverlight application using MEF.
you can find more about the MEF on part 1, part 2 and part 3 of this series.
this post is written on Visual Studio 2010 and Silverlight 4.0 (using Visual studio 2008 and Silverlight 3
will need some minor modification and download the MEF Silverlight 3 bits from the MEF site).
the code sample for this post can be download from here.
if you want to start from our previous post code, you can download it from here.
Step 1: Download the Silverlight 4 Beta Toolkit
downloading a-sync Silverlight Packages (XAP) does not include in in the box at this point (i hope it will on the release time),
so you have to download the Silverlight 4 Beta Toolkit, which you can download here. You’ll need latter on this post.
Step 2: Create XAP (Silverlight App) for the new plug-in
the a-sync discovery technique that we are going to use in this post, will search for plug-ins in XAP files
that was deployed at the same virtual folder as our shell application deployed.
therefore we have to create Silverlight application rather then Silverlight class library.
create Silverlight application.
before approving the new application you have to uncheck the "make it the start page" check box
so it will keep the current Silverlight application as the startup application.
Step 2.1: delete the App.xaml
delete the app.xaml from the plug-in application, we don't need it there.
Step 3: add reference to MEF
before adding the plug-able functionality, we have to add reference to MEF.
add new reference and browse for System.ComponentModel.Composition.dll under the following folder:
64 bit: C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client
32 bit: C:\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client
Step 4: Change the main page xaml (plug-in application)
at the plug-in application that we created in the previous step, change the MainPage.xaml to:
Code Snippet
- <Grid x:Name="LayoutRoot" Background="White">
- <Button Command="{Binding}" Width="Auto" Height="Auto">
- <TextBlock Text="External plug"/>
- </Button>
- </Grid>
we are using the main page as our plug-in.
Step 5: Expose the plug-in
go the the code behind of the plug-in MainPage.xaml and decorate the class with the following Export attribute:
Code Snippet
- [Export(typeof(UserControl))]
- public partial class MainPage : UserControl, ICommand
- {
- public MainPage()
- {
- InitializeComponent();
-
- DataContext = this;
- }
add using to System.ComponentModel.Composition
and set the DataContext to this.
Step 5.1: Add Imports
adding imports for the exposed shell TextBlock and Border.
Code Snippet
- [Import]
- public TextBlock ShellText { get; set; }
-
- [Import]
- public Border ShellBorder { get; set; }
Step 6: implement the ICommand interface
add the ICommand to the inheritance of the class and implement the interface.
the Execute method should look like the following code:
Code Snippet
- public void Execute(object parameter)
- {
- ShellText.Text = "External plug";
- ShellText.FontSize = 32.0;
- ShellBorder.Background = new SolidColorBrush(Colors.Yellow);
- var grdCol = new GradientStopCollection();
- grdCol.Add (new GradientStop { Color=Colors.Green, Offset=0});
- grdCol.Add (new GradientStop { Color=Colors.Purple, Offset=0.25});
- grdCol.Add (new GradientStop { Color=Colors.Orange, Offset=0.5});
- grdCol.Add (new GradientStop { Color=Colors.Blue, Offset=0.75});
- var brush = new LinearGradientBrush (grdCol,45);
- ShellText.Foreground = brush;
- }
Step 7: A-Sync composition
add reference to the System.ComponentModel.Composition.Packaging.Toolkit.dll to the shell project
you should find it at:
C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Toolkit\Nov09\Bin\System.ComponentModel.Composition.Packaging.Toolkit.dll for 64 bit
C:\Program Files\Microsoft SDKs\Silverlight\v4.0\Toolkit\Nov09\Bin\System.ComponentModel.Composition.Packaging.Toolkit.dll for 32 bit
Step 7.1: Allow Recomposition
the a-sync composition will result in re-adding plug-ins to the existing plug-ins collection,
this behavior required to modify the Import policy to allow recomposition.
at the shell project, MainPage.xaml code behind, modify the import declaration to:
Code Snippet
- [ImportMany (AllowRecomposition=true)]
- public ObservableCollection<UserControl> ToolbarItems { get; set; }
Step 7.2: Minor changes to the InitializeContainer method
because we will need the PackageCatalog latter for adding the new
discovered packages we have to take it out to the class level scope.
at the app.xaml code behind , change the InitializeContainer method as follow:
Code Snippet
- PackageCatalog _catalogs = new PackageCatalog();
- private void InitializeContainer(UIElement mainWin)
- {
- _catalogs = new PackageCatalog();
- _catalogs.AddPackage(Package.Current);
- var mainWinPart = AttributedModelServices.CreatePart(mainWin);
- var batch = new CompositionBatch(new[] { mainWinPart }, null);
- var container = new CompositionContainer(_catalogs);
- container.Compose(batch);
- }
Step 7.3: Loading external plug-ins
Code Snippet
- private void Application_Startup(object sender, StartupEventArgs e)
- {
- this.RootVisual = new MainPage();
- InitializeContainer(this.RootVisual);
- var uri = new Uri("MyPlugIn.xap", UriKind.Relative);
- Package.DownloadPackageAsync(uri,
- (args, p) =>
- {
- Thread.Sleep(3000);// just waiting in order to emphasize the a-sync effect
- _catalogs.AddPackage(p);
- });
- }
lines 5-11 are responsible for the a-sync package loading.
Summary
the a-sync pattern is really powerful, and we can benefit from better startup time of the
Silverlight application by pushing heavy loading into plug-able components (which will be loaded a-sync).
another benefit is the capability of on demand plug-ins loading.
Downloads
the code sample for this post can be download from here.
you will need Silverlight 4 and the Silverlight 4 toolkit. You can download Silverlight 4 beta here and the toolkit here.
Learn More
you can find more information on how to use MEF over Silverlight in the following posts (by Glenn Block):
Building Hello MEF – Part III – XAP Partitioning (with the host’s permission) and the sweetness of recomposition.
Point of Interest
if you living in Israel you can hear me speaking about MEF at the SDP at Monday 28.12.2009 (mark your calendar)

Pocket MEF is now supporting Windows CE
One of our customer (at SELA Group) was asking for MEF solution that targeting the Windows CE platform.
so after short discussion with Noam Sheffer we decide that it will be nice to add this capability into Packet MEF.
in matter of fact i was able to add this new capability almost without having to change the Pocket MEF code at all.
in case that you are working on Windows CE solution and want to have MEF capabilities,
you can download it from the Pocket MEF space at codeplex.
SELA Developer Practice – Extensibility
at the end of the second day on SELA Developer Practice (28th of December )
I will present a session that will focus on the .NET 4.0 Extensibility (MEF)
and how can you use it for building composite application using WPF 4.0.
prior to this session Tomer Shamam will have few session about WFP 4.0.
each day of the SELA Developer Practice is having 3 parallel tracks,
some of the tracks happens at SELA university (our sessions happens at SELA)

other at Crowne Plaza Hotel (Hayarkon 145 Tel-Aviv).

Get tune, do not miss this knowledge opportunity.
Click here for more details and registration


MEF for Beginner – Part 3 (Hello Silverlight)
in this post we will cover the basic steps that is needed for building your first Silverlight MEF application.
you can find more about the MEF on part 1, part 2 of this series, the series TOC is available here.
the following instructions will lead you through very simple steps of building simple Silverlight shell application
that can consume plug-ins.
this post is written on Visual Studio 2010 and Silverlight 4.0 (using Visual studio 2008 and Silverlight 3
will need some minor modification and download the MEF Silverlight 3 bits from the MEF site).
in the next post on this series, we will extend the current post by learning how to consume external plug-ins using a-sync loading .
the code sample for this post can be download from here.
Step 1: Creating Silverlight Application
Create solution using the Silverlight application template.
Step 2: Setting the Shell layout
the layout of the shell will have 2 area (plug-in command area and main area):
the plug-ins commands will host in StackPanel control
and the main content area will have a Border and TextBlock controls within a Canvas.
add the following Xaml into the Grid element of the main page.
Code Snippet
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="150" />
- <ColumnDefinition Width="308*" />
- </Grid.ColumnDefinitions>
- <StackPanel Orientation="Vertical" Grid.Column="0">
- </StackPanel>
- <Canvas x:Name="_mainContentPlaceHolder" Grid.Column="1" >
- <Border x:Name="_mainBorder" Width="250" Height="100" BorderThickness="1" CornerRadius="1" Margin="4">
- <TextBlock x:Name="_mainText" Text="Some content"/>
- </Border>
- </Canvas>
Step 3: Binding the StackPanel to plug-ins list
add the ItemControl element into the StackPanel (see it's binding definition)
Code Snippet
- <StackPanel Orientation="Vertical" Grid.Column="0">
- <ItemsControl ItemsSource="{Binding Path=ToolbarItems}" />
- </StackPanel>
add ObservableCollection of UserControl property called ToolbarItems into the Shell code behind
(the binding definition at the Xaml level refer to this property)
Code Snippet
- public ObservableCollection<UserControl> ToolbarItems { get; set; }
initialize the ToolbarItems property and the Context at the constructor,
(the following lines should be add to the constructor).
Code Snippet
- ToolbarItems = new ObservableCollection<UserControl>();
- DataContext = this;
Step 4: add reference to MEF
before adding the plug-able functionality, we have to add reference to MEF.
add new reference and browse for System.ComponentModel.Composition.dll under the following folder:
64 bit: C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client
32 bit: C:\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client
Step 5: decorate the ToolbarItems property
decorating the ToolbarItems property with ImportMany attribute, will shift the responsibility of
filling it with UserControl instances to MEF (which is basically saying to MEF
that it should add any item that was Export and match the contract (in our case UserControl).
the ToolbarItems should now look like this:
Code Snippet
- [ImportMany]
- public ObservableCollection<UserControl> ToolbarItems { get; set; }
Step 6: expose the Element within the main area
the shell will expose the Border and the TextBlock within it main area so it can be
discoverable by the plug-ins.
to achieve this task we will add 2 properties (at the code behind) and decorate it with Export attribute.
Code Snippet
- [Export]
- public TextBlock MainText
- {
- get { return _mainText; }
- }
-
- [Export]
- public Border MainBorder
- {
- get { return _mainBorder; }
- }
Step 7: Create exportable entities (create plug-ins)
Note: on this post we will add the plug-ins within the same package as our Shell,
but in the next post in this series we will show how to discover exportable
parts within external packages.
Create Parts folder in the project and add Silverlight User Control (PlugableEffect1.xaml)
Step 7.1: Stet the look and feel of the effect command
add the following Xaml into the Grid element (of the effect xaml)
Code Snippet
- <Button Command="{Binding}" Width="Auto" Height="Auto">
- <TextBlock Text="Effect 1"/>
- </Button>
Step 7.2: Add TextBlock property that present the TextBlock at the Shell main area
also this plug-in is capable of manipulate a TextBlock, it shouldn't be aware of
the TextBlock origin.
to achieve the above requirements we will once again add decorated property,
which will be assigned by MEF at runtime.
this time we expecting single value, therefore we will decorate the property with the Import attribute
rather the ImportMany attribute.
Note: MEF will find the exported TextBlock which we expose at step 6 and assign it into the following property.
Code Snippet
- [Import]
- public TextBlock ShellText { get; set; }
Step 7.3: Set the effect command
looking at the Xaml of the button we can see that it use the Command="Binding"
this mean that the button expect ICommand implementation within it's data context.
at the code behind of this effect, add the following line to the constructor.
and implement ICommand
Code Snippet
- public partial class PlagableEffect1 : UserControl, ICommand
Code Snippet
- public bool CanExecute(object parameter)
- {
- return true;
- }
-
- public event EventHandler CanExecuteChanged;
-
- public void Execute(object parameter)
- {
- ShellText.Text = "Effect 1";
- ShellText.FontSize = 32.0;
- ShellText.Foreground = new SolidColorBrush(Colors.Red);
- ShellText.FontFamily = new FontFamily("Comic Sans MS");
- }
Step 7.4: Export our effect
making the effect visible to MEF done by decorating the class with Export attribute.
Code Snippet
- [Export(typeof(UserControl))]
- public partial class PlugableEffect1 : UserControl, ICommand
Step 8: Create another exportable entities (create plug-ins)
repeat step 7 for Effect 2 (replace the Effect 1 text to Effect 2).
then add another property decorated with Import for the shell Border element.
Code Snippet
- [Import]
- public Border ShellBorder { get; set; }
replace the Execute method implementation of the Effect 2 command to the following:
Code Snippet
- public void Execute(object parameter)
- {
- ShellText.Text = "Effect 2";
- ShellText.FontSize = 24.0;
- ShellText.Foreground = new SolidColorBrush(Color.FromArgb(255, 33, 33, 33));
- ShellText.FontFamily = new FontFamily("Comic Sans MS");
- ShellText.FontWeight = FontWeights.ExtraBold;
- ShellText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
- ShellText.HorizontalAlignment = HorizontalAlignment.Center;
-
- ShellBorder.BorderThickness = new Thickness(8);
- ShellBorder.BorderBrush = new SolidColorBrush(Colors.Gray);
- ShellBorder.CornerRadius = new CornerRadius(10.0);
- ShellBorder.Background = new SolidColorBrush(Colors.Orange);
- ShellBorder.Width = 250;
- var rt = new RotateTransform();
- rt.Angle = 45;
- rt.CenterX = 1.5;
- rt.CenterY = 30;
- ShellBorder.RenderTransform = rt;
- }
Step 9: Compose it all together
before we continue we have to add reference to System.ComponentModel.Composition.Packaging.Toolkit.dll
this dll is part of the MEF Silverlight Toolkit
after installing the toolkit you can find the System.ComponentModel.Composition.Packaging.Toolkit.dll
at C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Toolkit\Nov09\Bin (for 64 bit)
and at C:\Program Files\Microsoft SDKs\Silverlight\v4.0\Toolkit\Nov09\Bin (for 32 bit)
Step 9.1: Compose
the last step involve is asking MEF to compose.
we will supply MEF with some basics instruction and ask it to assign all the Import with
Export that matches the Import's needs.
Add the following method to the App.xaml code behind.
Code Snippet
- private void InitializeContainer(UIElement mainWin)
- {
- var catalogs = new PackageCatalog();
- catalogs.AddPackage(Package.Current);
- var mainWinPart = AttributedModelServices.CreatePart(mainWin);
- var batch = new CompositionBatch(new[] { mainWinPart }, null);
- var container = new CompositionContainer(catalogs);
- container.Compose(batch);
- }
the above code create a Catalog (at lines 3,4) ,
Catalog used as instruction for where to search for the compose-able parts.
in this case we instruct MEF to look for compose-able parts within the current Silverlight package.
at lines 5,6 we add the current instance of the Shell into CompositionBatch, this will instruct the MEF container
to use this instance rather of creating new one.
line 7, 8 add the Catalog and the CompositionBatch to a CompositionContainer and perform the composition.
the last peace of code is calling the above method from the application startup.
Code Snippet
- private void Application_Startup(object sender, StartupEventArgs e)
- {
- this.RootVisual = new MainPage();
- InitializeContainer(this.RootVisual);
- }
Summary
this post had demonstrate how to build compose-able shell using Silverlight 4.0.
in the next post we will continue to enhance the sample by adding a-sync loading capability
to external Silverlight packages that holding compose-able parts (Plug-ins).
Downloads
the code sample for this post can be download from here.
you will need Silverlight 4 and the Silverlight 4 toolkit. You can download Silverlight 4 beta here and the toolkit here.
Learn More
you can find more information on how to use MEF over Silverlight in the following posts (by Glenn Block):
Building the Hello MEF dashboard in Silverlight 4 - Part I
Building Hello MEF – Part II – Metadata and why being Lazy is a good thing.
Building Hello MEF – Part III – XAP Partitioning (with the host’s permission) and the sweetness of recomposition.
Updates
the MEF API for Silverlight Catalog has changed,
instead using the PackageCatalog you should now use the DeploymentCatalog.
other changes were:
PartIntializer renamed to CompositionInitializer (Silverlight only)
and PartCreator renamed to ExportFactory<T> and moved to System.ComponentModel.Composition.Initialization assembly (Silverlight only)
Pocket MEF CTP 8
I finally found the time for updating Pocket MEF to the CTP 8 version.
the new version is available on codeplex.
if you were using the previous version I encourage you to switch to this version.
this version is match closer to the full framework version bits and it is better testes.
What's new on this version?
Pocket.ComponentModel.Initialization
Pocket.ComponentModel.Initialization is now supported:
PartInitializer:
you can use the PartInitializer to satisfy your object without having instance of the container.
the difference from the Silverlight version is that the entry assembly is not part of the default container's catalog.
the only default catalog is Parts relative directory which you can drop compostable assemblies without needs for custom setting.
CompositionHost:
the CompositionHost can be use for setting the default container (which is used by the PartInitializer)
see the following code snippet (place the initialization code at the start of the Main method):
Code Snippet
- var catalogs = new AggregateCatalog();
- var catalogAssembly = new AssemblyCatalog(Assembly.GetExecutingAssembly());
- var catalogFolder = new DirectoryCatalog(PLUG_INS_FOLDERS);
- catalogs.Catalogs.Add(catalogAssembly);
- catalogs.Catalogs.Add(catalogFolder);
- var container = new CompositionContainer(catalogs);
- CompositionHost.InitializeContainer(container);
Metadata support:
the next major change of this version is the metadata support.
using strong typed metadata on the full framework version is using Reflection.Emit which is not supported on the Compact Framework.
to resolve this issue you should register a mapper that know how to convert the metadata into your strongly typed instance.
the mapper should implement the following interface:
Code Snippet
- internal interface IMetadataViewProvider<TMetadataView>
- {
- TMetadataView GetMetadataView(IDictionary<string, object> metadata);
- }
use the following sample for registering the mapper into the framework:
Code Snippet
- MetadataViewProvider.RegisterProvider<ICustomMetadata>(MetadataViewProvider_ICustomMetadata.Instance);
to make the mapper creation task easier you can find code snippet that will help you with that task,
the code snippet available both as part of the source code and as separate download
Point of interest
if you living in Israel you can hear me speaking on MEF at the SDP

Code Cartoon – MEF principles


Point of interest
if you living in Israel you can hear me speaking on MEF at the SDP
(actually this lecture isn't yet updated in the syllabus but i believe that it will in a few days)

MEF for Beginner – Part 2 (VS 2008)
How To build your first MEF application
in this post we will cover the basic steps that is needed for building your first MEF application.
you can find more about the MEF concept on part 1 of this series.
the next following instructions will lead you through very simple steps of building simple Logger application.
this post is written on Visual Studio 2008, use this link for the Visual studio 2010 version.
the Silverlight version will be discuss on the part 3.
Step 1: create new console application
Step 2: add reference
previous to the .NET 4.0 MEF does not include in the CLR, therefore adding reference to MEF involve
step 2.1 and 2.2 or download the System.ComponentModel.Composition.dll from here.
Step 2.1
one extra step of downloading the MEF source code from http://mef.codeplex.com/
Step 2.2
open the MEF.sln and compile the and build the ComponentModel project
Step 2.3
add reference to System.ComponentModel.Composition.dll
Step 3: Create the ILogger interface
the ILogger interface will latter use as a contract.
Code Snippet
- public interface ILogger
- {
- void Write(string message);
- }
Step 4: Write the logger implementation
the following code show simple logger implementation for logging to the EventLog, Console and the Debug.
Code Snippet
- public class ConsoleLogger: ILogger
- {
- void ILogger.Write(string message)
- {
- Console.WriteLine(message);
- }
- }
- public class DebugLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- Debug.WriteLine(message);
- }
- }
- public class EventLogLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- EventLog.WriteEntry("MEFSample", message);
- }
- }
Step 5: Create proxy to the logger service
Code Snippet
- public class LoggerProxy
- {
- private static LoggerProxy _logger;
-
- static LoggerProxy()
- {
- _logger = new LoggerProxy();
- }
-
- private ILogger[] Loggers { get; set; }
-
- public static void Write(string message)
- {
- foreach (var logger in _logger.Loggers)
- {
- logger.Write(message);
- }
- }
- }
Let's see what do we have so far
so far we having all the parts needed for our simple logging solution.
but we lack the glue to bind those parts (how do the logger proxy will discover and initialize its loggers?).
MEF as a glue

In the next steps we will see how MEF can be used
to glue the parts together (without coupling the
different parts).
Step 6: Decorating the parts
out of the box MEF having very simple and friendly attribute model,
which can be used to decorate our Exported parts (the part that we want to be discoverable),
and our Imports (the units (properties for example) that needed those parts).
Note: MEF does not dictate the decoration (attribute) model.
Step 6.1: Decorating the Exported parts
the following code is using the Export attribute for decorating the part
that should be exposed while asking for the ILogger (contract).
Code Snippet
- [Export(typeof(ILogger))]
- public class ConsoleLogger: ILogger
- {
- void ILogger.Write(string message)
- {
- Console.WriteLine(message);
- }
- }
- [Export(typeof(ILogger))]
- public class DebugLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- Debug.WriteLine(message);
- }
- }
- [Export(typeof(ILogger))]
- public class EventLogLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- EventLog.WriteEntry("MEFSample", message);
- }
- }
Step 6.2: Decorating the needs
the following code is using the ImportMany attribute decoration,
to inform the MEF infrastructure that the Loggers property should assign with the parts that match
the ILogger contract.
Code Snippet
- [ImportMany]
- public ILogger[] Loggers { get; private set; }
Step 7: Composition
Note: decoration by itself does nothing but attaching declaration to code units.
the following code illustrate how to start the MEF composition process.
the following steps occurs at the static constructor:
Create instance of the _logger (singleton pattern)
Create catalog (that telling MEF where to look for parts discovery)
Create container (host), and handing the catalog.
Call the ComposeParts method of the container (this is where the Logger property get assigned with the discovered loggers).
the ComposeParts gets the _logger (that way the composition will act upon the _logger instance instead of creating another.
Code Snippet
- public class LoggerProxy
- {
- private static LoggerProxy _logger;
-
- static LoggerProxy()
- {
- _logger = new LoggerProxy();
- var catalog = new AssemblyCatalog(typeof(LoggerProxy).Assembly);
- var container = new CompositionContainer(catalog);
- container.ComposeParts(_logger);
- }
-
- [ImportMany]
- public ILogger[] Loggers { get; private set; }
-
- public static void Write(string message)
- {
- foreach (var logger in _logger.Loggers)
- {
- logger.Write(message);
- }
- }
- }
Download
the code for this post available here.
Summary
further on this series i will discuss the Silverlight version for MEF and some we will continue to explore many
other aspect of the MEF framework like Metadata, Lifetime management, Catalogs, Initialization techniques, Pocket MEF and match more.
Point of interest
if you living in Israel you can hear me speaking on MEF at the SDP
(actually this lecture isn't yet updated in the syllabus but i believe that it will in a few days)

MEF for Beginner – Part 2 (VS 2010)
How To build your first MEF application
in this post we will cover the basic steps that is needed for building your first MEF application.
you can find more about the MEF concept on part 1 of this series.
the next following instructions will lead you through very simple steps of building simple Logger application.
this post is written on Visual Studio 2010, use this link for the Visual studio 2008 version.
the Silverlight version will be discuss on the part 3.
Step 1: create new console application
Step 2: add reference
add reference to System.ComponentModel.Composition (MEF is part of the CLR starting from CLR 4.0)
Step 3: Create the ILogger interface
the ILogger interface will latter use as a contract.
Code Snippet
- public interface ILogger
- {
- void Write(string message);
- }
Step 4: Write the logger implementation
the following code show simple logger implementation for logging to the EventLog, Console and the Debug.
Code Snippet
- public class ConsoleLogger: ILogger
- {
- void ILogger.Write(string message)
- {
- Console.WriteLine(message);
- }
- }
- public class DebugLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- Debug.WriteLine(message);
- }
- }
- public class EventLogLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- EventLog.WriteEntry("MEFSample", message);
- }
- }
Step 5: Create proxy to the logger service
Code Snippet
- public class LoggerProxy
- {
- private static LoggerProxy _logger;
-
- static LoggerProxy()
- {
- _logger = new LoggerProxy();
- }
-
- private ILogger[] Loggers { get; set; }
-
- public static void Write(string message)
- {
- foreach (var logger in _logger.Loggers)
- {
- logger.Write(message);
- }
- }
- }
Let's see what do we have so far
so far we having all the parts needed for our simple logging solution.
but we lack the glue to bind those parts (how do the logger proxy will discover and initialize its loggers?).
MEF as a glue

In the next steps we will see how MEF can be used
to glue the parts together (without coupling the
different parts).
Step 6: Decorating the parts
out of the box MEF having very simple and friendly attribute model,
which can be used to decorate our Exported parts (the part that we want to be discoverable),
and our Imports (the units (properties for example) that needed those parts).
Note: MEF does not dictate the decoration (attribute) model.
Step 6.1: Decorating the Exported parts
the following code is using the Export attribute for decorating the part
that should be exposed while asking for the ILogger (contract).
Code Snippet
- [Export(typeof(ILogger))]
- public class ConsoleLogger: ILogger
- {
- void ILogger.Write(string message)
- {
- Console.WriteLine(message);
- }
- }
- [Export(typeof(ILogger))]
- public class DebugLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- Debug.WriteLine(message);
- }
- }
- [Export(typeof(ILogger))]
- public class EventLogLogger : ILogger
- {
- void ILogger.Write(string message)
- {
- EventLog.WriteEntry("MEFSample", message);
- }
- }
Step 6.2: Decorating the needs
the following code is using the ImportMany attribute decoration,
to inform the MEF infrastructure that the Loggers property should assign with the parts that match
the ILogger contract.
Code Snippet
- [ImportMany]
- public ILogger[] Loggers { get; private set; }
Step 7: Composition
Note: decoration by itself does nothing but attaching declaration to code units.
the following code illustrate how to start the MEF composition process.
the following steps occurs at the static constructor:
Create catalog (that telling MEF where to look for parts discovery)
Create container (host), and handing the catalog.
Call the Compose method of the container (this is where the Logger property get assigned with the discovered loggers).
the final step is to gets the _logger from the container (notice that the LoggerProxy class is decorated with Export attribute)
Note: at this stage we will ignore the CompositionBatch because it will likely be removed from the release version.
Code Snippet
- [Export]
- public class LoggerProxy
- {
- private static LoggerProxy _logger;
-
- static LoggerProxy()
- {
- var batch = new CompositionBatch();
- var catalog = new AssemblyCatalog(typeof(LoggerProxy).Assembly);
- var container = new CompositionContainer(catalog);
- container.Compose(batch);
-
- _logger = container.GetExportedValue<LoggerProxy>();
- }
-
- [ImportMany]
- public ILogger[] Loggers { get; private set; }
-
- public static void Write(string message)
- {
- foreach (var logger in _logger.Loggers)
- {
- logger.Write(message);
- }
- }
- }
actually the VS 2010 MEF version is one step behind the MEF CTP 8,
so the composition stag will may handle slightly different in the release version
(see the MEF CTP 8 version of this post)
Download
the code for this post available here.
Summary
further on this series i will discuss the Silverlight version for MEF and some we will continue to explore many
other aspect of the MEF framework like Metadata, Lifetime management, Catalogs, Initialization techniques, Pocket MEF and match more.
Point of interest
if you living in Israel you can hear me speaking on MEF at the SDP
(actually this lecture isn't yet updated in the syllabus but i believe that it will in a few days)
