MEF 101 - Part1

The Managed Extensibility framework or MEF is a framework released as part of .NET 4 and Silverlight that provides a mechanism to dynamically compose an application at runtime out of loosely coupled parts and provides a variety of mechanisms to discovering these parts. You can think of this as an implementation of a plugin framework that enables plugging in functionality into a container, based on information available at runtime. The most notable example of a MEF client is the Visual Studio 2010 editor which uses MEF to plugin in 3rd party extensions into it's shell proving an easy to use programming model to customize and/or extend the behavior of the IDE.

To wrap my head around MEF and how to leverage the framework to write extensible apps,I'll be going over some of the key features and APIs in MEF over the next several posts. This is the first in the series, and covers the nuts and bolts that MEF is made up of:

Imports and Exports

Imports and Exports is how MEF discovers and marries components that provide a service with components needing a service. The discovery is based on attributes.
A type decorated with the [Export] attribute indicates to MEF that the type is available to any type that needs it's services. Similarly a type needing a service is decorated with the [Import] attribute which conveys to MEF that it is in need of some type which provides the service.

Using Concrete classes

To make things a bit concrete, let's say we have a Logger which uses a TextFormatter to format messages before they are logged.

  1. [Export]  
  2. public class TextFormatter  
  3. {  
  4.     public string Format(string str)  
  5.     {  
  6.         return string.Format("Formatted Message:{0}", str);  
  7.     }  
  8. }  
  9.   
  10. [Export]  
  11. public class ConsoleLogger  
  12. {  
  13.     [Import]  
  14.     TextFormatter Formatter  
  15.     {  
  16.         get;  
  17.         set;  
  18.     }  
  19.   
  20.     public void Log(string str)  
  21.     {  
  22.         string formattedString = Formatter.Format(str);  
  23.         Console.WriteLine(formattedString);  
  24.     }  
  25. }  

The [Export] attribute on the TextFormatter class indicates that the services of this type are available to any type that needs them. The [Import] attribute on the ConsoleLogger indicates that it needs a TextFormatter in order for it to log messages.
Similarly the [Export] attribute on the ConsoleLogger indicates that it's services are available to any type that needs a ConsoleLogger.

  1. class Program  
  2. {  
  3.     [Import]  
  4.     public ConsoleLogger Logger { getset; }  
  5.   
  6.     static void Main(string[] args)  
  7.     {  
  8.         Program p = new Program();  
  9.         CompositionContainer container =   
  10.             new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));  
  11.           
  12.         container.ComposeParts(p);  
  13.         p.Logger.Log("This is a test");  
  14.     }  
  15. }  

Nowhere in the code above do you see a new TextFormatter() or new ConsoleLogger().
MEF handles the creation for you. In order to do this it needs to discover the types available so that it can satify the imports. It does this using a CompositionContainer which holds onto catalogs of various types. A catalog itself is a container holding types. In the code above we are using one type of catalog called AssemblyCatalog which wraps around a specified assembly and holds onto the types available in the assembly which exports services that can be used for satisfying imports(more on catalogs later). The main program imports the ConsoleLogger, in order to satisfy this import and have MEF create a ConsoleLogger for us we need to tell MEF to go through a composition on the instance of the Program so that it can satify it's imports. This is achieved via the call to container.Composeparts(p). At the end of this step MEF has inspected the current assembly, discovered that TextFormatter exports it's services which are needed in turn by the ConsoleLogger and injected an instance of the TextFormatter into the ConsoleLogger.
Furthermore, it then creates an instance of the ConsolLogger(since it also is an [Export]) and has injected an intance of the ConsoleLogger into the intance of the main program we created.

You might say "Why can't I just use new...?" which is a valid question, considering that everything is currently in one code file/assembly, this will become clearer as we progress further along where not all types are available in the same assembly and there is no static dependency between assemblies(via add ref).

Injecting dependencies via Constructor Injection

Imports can also be specified on constructors so that dependencies can be auto injected into a type. This is specified by using the [ImportingConstructor] attribute on the constructor of the type into which the dependency needs to be injected.

  1. [Export]  
  2.    public class TextFormatter  
  3.    {  
  4.        public string Format(string str)  
  5.        {  
  6.            return string.Format("Formatted Message:{0}", str);  
  7.        }  
  8.    }  
  9.   
  10.    [Export]  
  11.    public class ConsoleLogger  
  12.    {  
  13.        TextFormatter _formatter;  
  14.   
  15.        [ImportingConstructor]  
  16.        public ConsoleLogger(TextFormatter formatter)  
  17.        {  
  18.            _formatter = formatter;  
  19.        }  
  20.   
  21.        public void Log(string str)  
  22.        {  
  23.            string formattedString = _formatter.Format(str);  
  24.            Console.WriteLine(formattedString);  
  25.        }  
  26.    }  
  27.   
  28.    class Program  
  29.    {  
  30.        [Import]  
  31.        public ConsoleLogger Logger { getset; }  
  32.   
  33.        static void Main(string[] args)  
  34.        {  
  35.            Program p = new Program();  
  36.            CompositionContainer container =   
  37.                new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));  
  38.              
  39.            container.ComposeParts(p);  
  40.            p.Logger.Log("This is a test");  
  41.        }  
  42.    }  

In the above code,the TextFormatter is specified as a constructor parameter to the ConsoleLogger. the [ImportingConstructor] attribute indicates to MEF that the TextFormatter needs to be injected into the ConsoleLogger.
As before, the ConsoleLogger has an [Export] attribute and is imported into the main Program as an Import. When the Program is composed, MEF finds the TextFormatter in the AssemblyCatalog (since it's in the current assembly) and uses that to satisfy the import for the ConsoleLogger's constructor.

Exporting types from a Factory class

In the previous examples we've specified the [Export] attribute on the type itself such as on the TextFormatter and ConsoleLogger classes, which in turn causes MEF to instantiate these types for satisfying imports. Instead, if we wanted to have a factory class in charge of creating instances of a type so that you have more control, and specify these types as the ones to use for satisfying an import, we can do something like so:

  1. class FormatterFactory  
  2.    {  
  3.        [Export]  
  4.        public TextFormatter Formatter  
  5.        {  
  6.            get  
  7.            {  
  8.                return new TextFormatter();  
  9.            }  
  10.        }        
  11.    }  

The Formatter property of the FormatterFactory provides a valid export to MEF. If another type needs to Import a TextFormatter, MEF is prepared to instantiate the FormatterFactory and invoke the "Formatter" property in order to satisy the import.

  1. public class TextFormatter   
  2. {  
  3.     public string Format(string str)  
  4.     {  
  5.         return string.Format("Formatted Message:{0}", str);  
  6.     }  
  7. }  
  8.   
  9. [Export]  
  10. public class ConsoleLogger  
  11. {  
  12.     [Import]  
  13.     TextFormatter Formatter  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }               
  18.   
  19.      public void Log(string str)  
  20.     {  
  21.      string formattedString = Formatter.Format(str);  
  22.      Console.WriteLine(formattedString);                                
  23.     }  
  24. }  
  25.   
  26. class Program  
  27. {  
  28.     [Import]  
  29.     public ConsoleLogger Logger { getset; }  
  30.   
  31.     static void Main(string[] args)  
  32.     {  
  33.         Program p = new Program();  
  34.         CompositionContainer container =   
  35.             new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));              
  36.         container.ComposeParts(p);  
  37.         p.Logger.Log("This is a test");  
  38.     }  
  39. }  

Notice that the [Export] atribute is no longer present on the TextFormatter, and the import in ConsoleLogger is satisfied by the FormatterFactory.

In addition to exporting a type from a property we can also have function exports. i.e the [Export] attribute is tagged onto a method

  1. class FormatterFactory  
  2.     {  
  3.         [Export]  
  4.         public TextFormatter Formatter  
  5.         {  
  6.             get  
  7.             {  
  8.                 return new TextFormatter();  
  9.             }  
  10.         }  
  11.   
  12.         [Export]  
  13.         public TextFormatter GetTextFormatter()  
  14.         {  
  15.             return new TextFormatter();  
  16.         }  
  17.          
  18.         [Export]  
  19.         public void WriteFormattedOutput(string str, Stream stream)  
  20.         {  
  21.             System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();  
  22.             var bytes = encoding.GetBytes(str);  
  23.             stream.Write(bytes,0,bytes.Length);  
  24.         }  
  25.     }  

This enables some interesting scenarios for import, such as lazy evaulation.The function export can be imported into a type by specifying a delegate type that matches the function signature, The signatures of GetTextFormatter() and WriteFormattedOutput(string str, Stream stream) match the delegates Func<TextFormatter> and Action<string, Stream> respectively. We can use these delegates to import these exports into the ConsoleLogger.

  1. public class TextFormatter   
  2. {  
  3.     public string Format(string str)  
  4.     {  
  5.         return string.Format("Formatted Message:{0}", str);  
  6.     }  
  7. }  
  8.   
  9. [Export]  
  10. public class ConsoleLogger  
  11. {  
  12.     [Import]  
  13.     TextFormatter Formatter  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.   
  19.     [Import]  
  20.     public Func<TextFormatter> FormatterFunc  
  21.     {  
  22.         get;  
  23.         private set;  
  24.     }         
  25.   
  26.     [Import]  
  27.     public Action<string, Stream> FormatterAction  
  28.     {  
  29.         get;  
  30.         private set;  
  31.     }  
  32.      
  33.     public void Log(string str)  
  34.     {  
  35.         string formattedString = Formatter.Format(str);  
  36.         Console.WriteLine(formattedString);                     
  37.         formattedString = FormatterFunc().Format(str);  
  38.         FormatterAction(str, Console.OpenStandardOutput());  
  39.         Console.WriteLine(formattedString);  
  40.     }  
  41. }  
  42.   
  43. class Program  
  44. {  
  45.     [Import]  
  46.     public ConsoleLogger Logger { getset; }  
  47.   
  48.     static void Main(string[] args)  
  49.     {  
  50.         Program p = new Program();  
  51.         CompositionContainer container =   
  52.             new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));              
  53.         container.ComposeParts(p);  
  54.         p.Logger.Log("This is a test");  
  55.     }  
  56. }  

Notice the following 2 lines in the Log method
formattedString = FormatterFunc().Format(str);
FormatterAction(str, Console.OpenStandardOutput());
FormatterFunc() invokes the GetTextFormatter() of the Export which gives us a TextFormatter on which we then invoke the Format method.
FormatterAction(str, Console.OpenStandardOutput()) invokes the WriteFormattedOutput method we exported passing in a string and the standard console stream.
This is immensely useful when you don't necessarily want MEF to materialize a value up front but rather provide a handle to a method which on invocation yields a value, but there are other ways to be lazy.

Using Interfaces instead of concrete classes

This far we've been using concrete classes for all exports and imports, i.e we've used ConsoleLogger and TextFormatter. This limits us to working only with these types. To promote loose coupling to any type, MEF also supports importing and exporting via interfaces. We can extract out the following interfaces from the ConsoleLogger and TextFormatter

  1. public interface ITextFormatter  
  2. {  
  3.     string Name { get;}  
  4.     string Format(string str);  
  5. }  
  6.   
  7. public interface ILogger  
  8. {  
  9.     string Name { get;}  
  10.     ITextFormatter Formatter {  getset;}  
  11.     void Log(string str);  
  12. }  

and have both classes implement the respective interface

  1. [Export(typeof(ITextFormatter))]  
  2. public class TextFormatter : ITextFormatter  
  3. {  
  4.     public string Name  
  5.     {  
  6.         get  
  7.         {  
  8.             return "Text Formatter";  
  9.         }  
  10.     }  
  11.   
  12.     public string Format(string str)  
  13.     {  
  14.         return string.Format("Formatted Message:{0}", str);  
  15.     }  
  16. }  
  17.   
  18. [Export(typeof(ILogger))]  
  19. public class ConsoleLogger : ILogger  
  20. {  
  21.     [Import]  
  22.     public ITextFormatter Formatter  
  23.     {  
  24.         get;  
  25.         set;  
  26.     }  
  27.   
  28.     public void Log(string str)  
  29.     {  
  30.         string formattedString = Formatter.Format(str);  
  31.         Console.WriteLine(formattedString);  
  32.     }  
  33.    
  34.     public string Name  
  35.     {  
  36.         get  
  37.         {  
  38.             return "Console Logger";  
  39.         }              
  40.     }  
  41.      
  42. }  

Notice that the Export attributes now export the respective interface types and not the concrete types anymore and the Import attributes are applied on properties of interface types

  1. class Program  
  2. {  
  3.     [Import]  
  4.     public ILogger Logger { getset; }  
  5.   
  6.     static void Main(string[] args)  
  7.     {  
  8.         Program p = new Program();  
  9.         CompositionContainer container =   
  10.             new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));  
  11.           
  12.         container.ComposeParts(p);  
  13.         p.Logger.Log("This is a test");  
  14.     }  
  15. }  

The main program now just works since MEF resolves the import by instantiating the concrete type on which the Export attribute is defined, types it to the specified interface type and uses the interface type to satisfy imports.

Lazy Imports

It's great that MEF instantiates and injects types to satisfy imports but there are times when you just don't need an import to be satisfied until the point in time at which you need the imported type. The default behavior with the Import attribute is that when a part is composed, imports are satisified and MEF has already created an instance of the type and injected them into your type. Based on the dynamics of how your type is used, the satisifed import may never get used, this means that you paid for something that you did not need but paid for it in anticipation of it's use. It could very well be that the export might be a type which consumes expensive resources, or needs to make a cross domain/ cross process call as part of it's construction, or pull data from a database to initialize itself to a usable state, which means that we paid a "lot" for anticipation. To alleviate this, MEF leverages the Lazy<T> type which is new in .NET 4.0 to allow for lazy instantiaion of types. Using Lazy<T> for an import instead of T, causes MEF to delay the instantiation of the type T until the Value property of the Lazy<T> is accessed.

If we replace the Import in the main Program to use Lazy<ILogger> instead of ILogger, we effectively delay the creation of the ConsoleLogger until the Value property is accessed for the first time.

  1. [Export(typeof(ILogger))]  
  2. public class ConsoleLogger : ILogger  
  3. {  
  4.     [Import]  
  5.     public ITextFormatter Formatter  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.   
  11.     public void Log(string str)  
  12.     {  
  13.         string formattedString = Formatter.Format(str);  
  14.         Console.WriteLine(formattedString);  
  15.     }  
  16.    
  17.     public string Name  
  18.     {  
  19.         get  
  20.         {  
  21.             return "Console Logger";  
  22.         }              
  23.     }  
  24.      
  25. }  
  26.   
  27. class Program  
  28. {  
  29.       
  30.   
  31.     [Import]  
  32.     public Lazy<ILogger> Logger { getset; }  
  33.   
  34.     static void Main(string[] args)  
  35.     {  
  36.         Program p = new Program();  
  37.         CompositionContainer container =   
  38.             new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));  
  39.           
  40.         container.ComposeParts(p);  
  41.         p.Logger.Value.Log("This is a test");  
  42.     }  
  43. }  

If you were to add a watch to the p.Logger.IsValueCreated, you would observe that it returns false.Once the Value property is accessed, IsValueCreated would return true.

Part Creation Policy

By default when MEF satisfies imports for a type(note the pluralization), it shares the instance that it creates from the export across all imports(i.e. it creates a singleton) and this is the default behvior. You can change this behavior on the importing side or the exporting side.

On the exporting side you can specify a PartCreationPolicy attribute on the type being exported indicating that a new instance should be created for satisying an import, by specifying a value of CreationPolicy.NonShared (the default that MEF uses is CreationPolicy.Shared)

  1. [Export(typeof(ILogger))]      
  2. [PartCreationPolicy(CreationPolicy.NonShared)]  
  3. public class ConsoleLogger : ILogger  
  4. {  
  5.     [Import]  
  6.     public ITextFormatter Formatter  
  7.     {  
  8.         get;  
  9.         set;  
  10.     }  
  11.   
  12.     public void Log(string str)  
  13.     {  
  14.         string formattedString = Formatter.Format(str);  
  15.         Console.WriteLine(formattedString);  
  16.     }  
  17.    
  18.     public string Name  
  19.     {  
  20.         get  
  21.         {  
  22.             return "Console Logger";  
  23.         }              
  24.     }  
  25.      
  26. }  

Now, whenever MEF satisfies an import it will create a new instance of the ConsoleLogger instead of a singleton.
You can also specify a value of CreationPolicy.Any which effectively means that the importer decides the creation policy.
This is accomplished by using an overload of the Import attribute which accepts a RequiredCreationPolicy enum,which can have values of Shared,NonShared or Any. This is best illustrated with an example:

  1. [Export(typeof(ILogger))]  
  2. [PartCreationPolicy(CreationPolicy.Any)]  
  3. public class ConsoleLogger : ILogger  
  4. {  
  5.     [Import]  
  6.     public ITextFormatter Formatter  
  7.     {  
  8.         get;  
  9.         set;  
  10.     }  
  11.   
  12.     public void Log(string str)  
  13.     {  
  14.         string formattedString = Formatter.Format(str);  
  15.         Console.WriteLine(formattedString);  
  16.     }  
  17.    
  18.     public string Name  
  19.     {  
  20.         get  
  21.         {  
  22.             return "Console Logger";  
  23.         }              
  24.     }  
  25.      
  26. }  
  27.   
  28. class Program  
  29. {  
  30.     [Import]  
  31.     public ILogger Logger1 { getset; }        
  32.   
  33.     [Import(RequiredCreationPolicy=CreationPolicy.Shared)]          
  34.     public ILogger Logger2 { getset; }  
  35.      
  36.     [Import(RequiredCreationPolicy=CreationPolicy.Shared)]  
  37.     public ILogger Logger3 { getset; }  
  38.   
  39.     [Import(RequiredCreationPolicy=CreationPolicy.NonShared)]  
  40.     public ILogger Logger4 { getset; }  
  41.   
  42.     static void Main(string[] args)  
  43.     {  
  44.         Program p = new Program();  
  45.         CompositionContainer container =   
  46.             new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));  
  47.           
  48.         container.ComposeParts(p);              
  49.     }  
  50. }  

Since Logger2 and Logger3 have a CreationPolicy of CreationPolicy.Shared, they will share an instance of a ConsoleLogger that MEF creates, Logger1 will also share this instance since the default behavior is Shared if nothing is specified.
Logger4 on the other hand uses a CreationPolicy of CreationPolicy.NonShared, which will cause MEF to create a new instance of the ConsolLogger4 for satisfying the import for Logger4. This instance is not shared with any other import.

Default Values

There may be times where there is no available export to satisfy an import and it might be feasible to settle with a default value for an import (null for a reference type and the default value for a value type).
If a Formatter is not available, the logger can still perform logging like so:

  1. public struct LogInfo  
  2.     {  
  3.         private string _loggedBy ;  
  4.   
  5.         public string LoggedBy  
  6.         {  
  7.             get { return _loggedBy; }  
  8.               
  9.         }  
  10.   
  11.         public LogInfo(string loggedBy)  
  12.         {  
  13.             _loggedBy = loggedBy;  
  14.         }         
  15.     }  
  16.   
  17.     [Export(typeof(ILogger))]  
  18.     public class ConsoleLogger : ILogger  
  19.     {  
  20.         [Import(AllowDefault=true)]  
  21.         public ITextFormatter Formatter  
  22.         {  
  23.             get;  
  24.             set;  
  25.         }  
  26.   
  27.         [Import(AllowDefault = true)]  
  28.         public LogInfo Info  
  29.         {  
  30.             get;  
  31.             set;  
  32.         }         
  33.   
  34.         public void Log(string str)  
  35.         {  
  36.   
  37.             if (Formatter != null)  
  38.             {  
  39.                 string formattedString = Formatter.Format(!string.IsNullOrEmpty(Info.LoggedBy)?  str + " logged by" + Info.LoggedBy: str);  
  40.                 Console.WriteLine(formattedString);  
  41.             }  
  42.         }  
  43.        
  44.         public string Name  
  45.         {  
  46.             get  
  47.             {  
  48.                 return "Console Logger";  
  49.             }              
  50.         }         
  51.     }  
  52.   
  53.     class Program  
  54.     {  
  55.         [Import]  
  56.         public ILogger Logger { getset; }              
  57.   
  58.         static void Main(string[] args)  
  59.         {  
  60.             Program p = new Program();  
  61.             CompositionContainer container =   
  62.                 new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));              
  63.             container.ComposeParts(p);              
  64.         }  
  65.     }  
Note that the [Import] ttribute sets "AllowDefault" to true which causes the Formatter property to be set to null since there are no types which export IFormatter and hence the Formatter is set to null.
Also note that for kicks we have included a struct (LogInfo) and the ConsoleLogger imports this struct. Since this struct is not explicitly exported and "AllowDefault = true", MEF creates a default instance of the struct and sets the "Info" property to this default instance.

Named Exports

Since multiple types can export the same contract you can provide a name for each export so that you can uniquely identify an export on the importing side like so:
  1. [Export("Console Loger",typeof(ILogger))]  
  2. public class ConsoleLogger : ILogger  
  3. {  
  4.     [Import]  
  5.     public ITextFormatter Formatter  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.   
  11.     public void Log(string str)  
  12.     {  
  13.         string formattedString = Formatter.Format(str);  
  14.         Console.WriteLine(formattedString);  
  15.     }  
  16.    
  17.     public string Name  
  18.     {  
  19.         get  
  20.         {  
  21.             return "Console Logger";  
  22.         }              
  23.     }         
  24. }  
  25.   
  26. [Export("Debug Logger",typeof(ILogger))]  
  27. public class DebugLogger : ILogger  
  28. {  
  29.     [Import(AllowDefault = true)]  
  30.     public ITextFormatter Formatter  
  31.     {  
  32.         get;  
  33.         set;  
  34.     }  
  35.   
  36.     public void Log(string str)  
  37.     {  
  38.         string formattedString = Formatter.Format(str);  
  39.         Debug.WriteLine(formattedString);              
  40.     }  
  41.   
  42.     public string Name  
  43.     {  
  44.         get  
  45.         {  
  46.             return "Debug Logger";  
  47.         }  
  48.     }  
  49. }  
  50. class Program  
  51. {  
  52.     [Import("Debug Logger")]  
  53.     public ILogger Logger { getset; }              
  54.   
  55.     static void Main(string[] args)  
  56.     {  
  57.         Program p = new Program();  
  58.         CompositionContainer container =   
  59.             new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));              
  60.         container.ComposeParts(p);             
  61.         p.Logger.Log(DateTime.UtcNow.ToString());             
  62.     }  
  63. }  
The main drawback here is that we are now rely on strings for identifying a particular export. There are better ways to achieve the same end effect using attributes as we'll soon see.

Import Many

The main advantage of MEF is building wholes out of parts and building functionality by assembling parts. Multiple types can implement the same contract and export it. You are not limited to importing a single implementation of an export,multiple implementations of a contract can be imported using [ImportMany] You could have different types of loggers,a ConsoleLogger to log to the console, a DebugLogger to log to the debug output and so on. These loggers can all export the ILogger interface. A client application can import many such ILoggers which causes MEF to look for all matching available exports in the configured catalogs to satisfy the import. This is specified using an ImportMany attribute an IEnumerable<ILogger> like so:

  1. [Export(typeof(ITextFormatter))]  
  2.     public class TextFormatter : ITextFormatter  
  3.     {  
  4.         public string Name  
  5.         {  
  6.             get  
  7.             {  
  8.                 return "Text Formatter";  
  9.             }  
  10.         }  
  11.   
  12.         public string Format(string str)  
  13.         {  
  14.             return string.Format("Formatted Message:{0}", str);  
  15.         }  
  16.     }  
  17.   
  18.     [Export(typeof(ILogger))]  
  19.     public class ConsoleLogger : ILogger  
  20.     {  
  21.         [Import]  
  22.         public ITextFormatter Formatter  
  23.         {  
  24.             get;  
  25.             set;  
  26.         }  
  27.   
  28.         public void Log(string str)  
  29.         {  
  30.             string formattedString = Formatter.Format(str);  
  31.             Console.WriteLine(formattedString);  
  32.         }  
  33.        
  34.         public string Name  
  35.         {  
  36.             get  
  37.             {  
  38.                 return "Console Logger";  
  39.             }              
  40.         }         
  41.     }  
  42.   
  43.     [Export(typeof(ILogger))]  
  44.     public class DebugLogger : ILogger  
  45.     {  
  46.         [Import(AllowDefault = true)]  
  47.         public ITextFormatter Formatter  
  48.         {  
  49.             get;  
  50.             set;  
  51.         }  
  52.   
  53.         public void Log(string str)  
  54.         {  
  55.             string formattedString = Formatter.Format(str);  
  56.             Debug.WriteLine(formattedString);              
  57.         }  
  58.   
  59.         public string Name  
  60.         {  
  61.             get  
  62.             {  
  63.                 return "Debug Logger";  
  64.             }  
  65.         }  
  66.     }  
  67.     class Program  
  68.     {  
  69.         [ImportMany]  
  70.         public IEnumerable<ILogger> Loggers { getset; }              
  71.   
  72.         static void Main(string[] args)  
  73.         {  
  74.             Program p = new Program();  
  75.             CompositionContainer container =   
  76.                 new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));              
  77.             container.ComposeParts(p);  
  78.             foreach (var logger in p.Loggers)  
  79.             {  
  80.                 logger.Log(DateTime.UtcNow.ToString());  
  81.             }  
  82.         }  
  83.     }  

Exporting Metadata

So now you've imported multiple exports,great!, you can use these exports as they are, but what if you needed to get a handle to a particular export you've imported. This is where metadata comes in. Each export can be annotated with export metadata which can be used to query the export.The metadata is made available on the import side as a Dictionary<string,object> which can be queried for the attribute name which is the dictionary key, and the value can be checked for the value of interest.
We can mark the ConsoleLogger as the default logger to use by specifying an ExportMetatdata attribute with key name "IsDefault" and value true.

  1. [Export(typeof(ITextFormatter))]  
  2.     public class TextFormatter : ITextFormatter  
  3.     {  
  4.         public string Name  
  5.         {  
  6.             get  
  7.             {  
  8.                 return "Text Formatter";  
  9.             }  
  10.         }  
  11.   
  12.         public string Format(string str)  
  13.         {  
  14.             return string.Format("Formatted Message:{0}", str);  
  15.         }  
  16.     }  
  17.   
  18.     [Export(typeof(ILogger))]  
  19.     [ExportMetadata("IsDefault"true)]  
  20.     public class ConsoleLogger : ILogger  
  21.     {  
  22.         [Import]  
  23.         public ITextFormatter Formatter  
  24.         {  
  25.             get;  
  26.             set;  
  27.         }  
  28.   
  29.         public void Log(string str)  
  30.         {  
  31.             string formattedString = Formatter.Format(str);  
  32.             Console.WriteLine(formattedString);  
  33.         }  
  34.        
  35.         public string Name  
  36.         {  
  37.             get  
  38.             {  
  39.                 return "Console Logger";  
  40.             }              
  41.         }         
  42.     }  
  43.   
  44.     [Export(typeof(ILogger))]  
  45.     [ExportMetadata("IsDefault"false)]  
  46.     public class DebugLogger : ILogger  
  47.     {  
  48.         [Import(AllowDefault = true)]  
  49.         public ITextFormatter Formatter  
  50.         {  
  51.             get;  
  52.             set;  
  53.         }  
  54.   
  55.         public void Log(string str)  
  56.         {  
  57.             string formattedString = Formatter.Format(str);  
  58.             Debug.WriteLine(formattedString);              
  59.         }  
  60.   
  61.         public string Name  
  62.         {  
  63.             get  
  64.             {  
  65.                 return "Debug Logger";  
  66.             }  
  67.         }  
  68.     }  

The client can query for the default logger like so:
  1. class Program  
  2.     {  
  3.         [ImportMany]  
  4.         public IEnumerable<Lazy<ILogger,Dictionary<string,object>>> Loggers { getset; }  
  5.   
  6.         public void LogUsingDefaultLogger(string message)  
  7.         {  
  8.             foreach (var logger in Loggers)  
  9.             {  
  10.                 if (logger.Metadata.ContainsKey("IsDefault"))  
  11.                 {  
  12.                     bool isdefault = (bool)logger.Metadata["IsDefault"];  
  13.                     if (isdefault)  
  14.                     {  
  15.                         logger.Value.Log(message);  
  16.                     }  
  17.                 }  
  18.             }  
  19.         }  
  20.   
  21.         static void Main(string[] args)  
  22.         {  
  23.             Program p = new Program();  
  24.             CompositionContainer container =   
  25.                 new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));              
  26.             container.ComposeParts(p);  
  27.             p.LogUsingDefaultLogger("test");  
  28.         }  
  29.     }  

Note that in order to get to the metadata the Loggers property is of type IEnumerable<Lazy<ILogger,Dictionary<string,object>>>, Lazy<T> exposes a Metadata property which allows us to get to our metadata as shown in LogUsingDefaultLogger

Exporting Metadata the strongly typed way

Working with strings tends to be error prone.Wouldn't it be nicer to export metadata using strong types instead of strings. The good news is you can.You can write a custom attribute class derived from ExportAttribute and includes properties in the derived class which you can then use for finding exports matching your filter criteria
  1. [MetadataAttribute]  
  2. [AttributeUsage(AttributeTargets.Class,AllowMultiple=false)]  
  3. public class LogExportAttribute : ExportAttribute  
  4. {  
  5.     public LogExportAttribute() : base(typeof(ILogger))  
  6.     {  
  7.   
  8.     }  
  9.   
  10.     public bool IsDefault { getset; }  
  11. }  

You can then decorate the loggers with this attribute and set one as the default
  1. [Export(typeof(ILogger))]  
  2. [LogExport(IsDefault=true)]  
  3. public class ConsoleLogger : ILogger  
  4. {  
  5.     [Import]  
  6.     public ITextFormatter Formatter  
  7.     {  
  8.         get;  
  9.         set;  
  10.     }  
  11.   
  12.     public void Log(string str)  
  13.     {  
  14.         string formattedString = Formatter.Format(str);  
  15.         Console.WriteLine(formattedString);  
  16.     }  
  17.    
  18.     public string Name  
  19.     {  
  20.         get  
  21.         {  
  22.             return "Console Logger";  
  23.         }              
  24.     }         
  25. }  
  26.   
  27. [Export(typeof(ILogger))]  
  28. [LogExport(IsDefault=false)]  
  29. public class DebugLogger : ILogger  
  30. {  
  31.     [Import(AllowDefault = true)]  
  32.     public ITextFormatter Formatter  
  33.     {  
  34.         get;  
  35.         set;  
  36.     }  
  37.   
  38.     public void Log(string str)  
  39.     {  
  40.         string formattedString = Formatter.Format(str);  
  41.         Debug.WriteLine(formattedString);              
  42.     }  
  43.   
  44.     public string Name  
  45.     {  
  46.         get  
  47.         {  
  48.             return "Debug Logger";  
  49.         }  
  50.     }  
  51. }  

In order to query for the attribute and reach into it's properties we need to also define an interface with properties corresponding to that of the custom attribute class like so:
  1. public interface ILogExportMetdata  
  2.    {  
  3.        bool IsDefault { get; }  
  4.    }  

We can then consume the metadata(strongly typed) like so:
  1. class Program  
  2.    {  
  3.        [ImportMany]  
  4.        public IEnumerable<Lazy<ILogger,ILogExportMetdata>> Loggers { getset; }  
  5.   
  6.        public void LogUsingDefaultLogger(string message)  
  7.        {  
  8.            foreach (var logger in Loggers)  
  9.            {  
  10.                if (logger.Metadata.IsDefault)  
  11.                {                      
  12.                    logger.Value.Log(message);                      
  13.                }  
  14.            }  
  15.        }  
  16.   
  17.        static void Main(string[] args)  
  18.        {  
  19.            Program p = new Program();  
  20.            CompositionContainer container =   
  21.                new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly()));              
  22.            container.ComposeParts(p);  
  23.            p.LogUsingDefaultLogger("test");  
  24.        }  
  25.    }  

Behind the scenes MEF performs some clever mapping of the attribute's properties to the interface's properties so that we can access the metadata in a strongly typed way.
This post is getting longer than I anticipated but we've covered the heart of what MEF is about.
In part 2 we'll look at Catalogs.

Print | posted @ Saturday, July 3, 2010 9:03 AM

Comments on this entry:

Gravatar # re: MEF 101 - Part1
by Jon Stonecash at 7/7/2010 8:38 AM

Decorating the ILogger classes with both Export and LogExport is redundant. This creates two entries in the Loggers list for each logger. In your example, it would cause each message to be logged twice.

Other than that, this was a very useful post. THX.
Gravatar # re: MEF 101 - Part1
by Sean Stapleton at 7/7/2010 1:01 PM

Outstanding overview, thank you so much. Look forward to pt 2.
Gravatar # re: MEF 101 - Part1
by Jone at 1/19/2011 9:33 AM

how to release shared instances created by MEF? for example, if any user logout from the silverlight application, when new login, I would like to recreate the shared instances that was created once.

Nice post.
Gravatar # re: MEF 101 - Part1
by Prabin at 10/28/2011 2:06 PM

Good job Abhijeet. It was just what I needed to get started with MEF. When are you coming up with the next part? Thanks!
Gravatar # re: MEF 101 - Part1
by Jeremy Brayton at 1/30/2013 12:03 PM

Thanks for this. I haven't even finished but once I got to the paragraph I'm about to paste, I had to comment. It's a problem I was currently struggling with until you explained it succinctly.

"You might say "Why can't I just use new...?" which is a valid question, considering that everything is currently in one code file/assembly, this will become clearer as we progress further along where not all types are available in the same assembly and there is no static dependency between assemblies(via add ref)."

The problem you describe was something that stumped me for way too long. How do I expose types at compile-time for an assembly I know nothing about? I almost went the hacky "Just throw the interface in the main contracts project!" which would've been completely sufficient as I'm not working on anything that needed to be completely exposed.

Thanks again for this, 2 years later...
Post A Comment
Title:
Name:
Email:
Comment:
Verification: