MEF for Beginner – Part 2 (VS 2008)


tags: ,
no comments

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


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
  1. public interface ILogger
  2. {
  3.     void Write(string message);
  4. }


Step 4: Write the logger implementation

the following code show simple logger implementation for logging to the EventLog, Console and the Debug.

Code Snippet
  1. public class ConsoleLogger: ILogger
  2. {
  3.     void ILogger.Write(string message)
  4.     {
  5.         Console.WriteLine(message);
  6.     }
  7. }
  8. public class DebugLogger : ILogger
  9. {
  10.     void ILogger.Write(string message)
  11.     {
  12.         Debug.WriteLine(message);
  13.     }
  14. }
  15. public class EventLogLogger : ILogger
  16. {
  17.     void ILogger.Write(string message)
  18.     {
  19.         EventLog.WriteEntry("MEFSample", message);
  20.     }
  21. }

Step 5: Create proxy to the logger service
Code Snippet
  1. public class LoggerProxy
  2. {
  3.     private static LoggerProxy _logger;
  5.     static LoggerProxy()
  6.     {
  7.         _logger = new LoggerProxy();
  8.     }
  10.     private ILogger[] Loggers { get; set; }
  12.     public static void Write(string message)
  13.     {
  14.         foreach (var logger in _logger.Loggers)
  15.         {
  16.             logger.Write(message);
  17.         }
  18.     }
  19. }


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
  1. [Export(typeof(ILogger))]
  2. public class ConsoleLogger: ILogger
  3. {
  4.     void ILogger.Write(string message)
  5.     {
  6.         Console.WriteLine(message);
  7.     }
  8. }
  9. [Export(typeof(ILogger))]
  10. public class DebugLogger : ILogger
  11. {
  12.     void ILogger.Write(string message)
  13.     {
  14.         Debug.WriteLine(message);
  15.     }
  16. }
  17. [Export(typeof(ILogger))]
  18. public class EventLogLogger : ILogger
  19. {
  20.     void ILogger.Write(string message)
  21.     {
  22.         EventLog.WriteEntry("MEFSample", message);
  23.     }
  24. }

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
  1. [ImportMany]
  2. 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
  1. public class LoggerProxy
  2. {
  3.     private static LoggerProxy _logger;
  5.     static LoggerProxy()
  6.     {
  7.         _logger = new LoggerProxy();
  8.         var catalog = new AssemblyCatalog(typeof(LoggerProxy).Assembly);
  9.         var container = new CompositionContainer(catalog);
  10.         container.ComposeParts(_logger);
  11.     }
  13.     [ImportMany]
  14.     public ILogger[] Loggers { get; private set; }
  16.     public static void Write(string message)
  17.     {
  18.         foreach (var logger in _logger.Loggers)
  19.         {
  20.             logger.Write(message);
  21.         }
  22.     }
  23. }



the code for this post available here.



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)


Digg This
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>