Click here to Skip to main content
11,925,292 members (60,175 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


24 bookmarked

MEF in .NET 4.5

, 27 Nov 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Advancements in MEF in .NET 4.5.


This article explains the problems with MEF1 and improvements in MEF2 (in .NET 4.5). Attached is a Visual Studio solution built in .NET 4.5.

Read the following articles for more on MEF:


The primary focus of MEF1 was extensibility, MEF allows to create an application such that application's different parts can be extended like a plug-in.

MEF1 has some problems...

  1. There was no way exporting types without giving them export attribute. This limitation has two consequences:
    • It was not possible to export types that you do not have access to the source code
    • While converting one existing application into an extensible MEF application, first all types need to be decorated with export attribute
  2. Control lifetime of an instance, as MEF1 has only two instance scopes:
    1. per instance and
    2. shared global lifetime
  3. Composition problems were not easy to diagnose.


MEF2 has solved the above problems:

  1. Attribute-less registration: One new class RegistrationBuilder is introduced that handles part creation and export registration automatically, it has solved both problems arising because the export attribute is required for type registration.

    RegistrationBuilder introduced three For*() methods as below that can identify/select parts to export.
    1. ForType(): selects a single type. In the code below, you can see how the type AnniversaryGreetings is exported and imported.
      //Export type
      //import type
      var anniGreeting = container.GetExportedValue<AnniversaryGreetings>();  
    2. ForTypesDerivedFrom(): selects types that are assignable to either a base class or an interface (the same as InheritedExport in MEF1) . In the code below, you can see how all types derived from IGreetings are exported and imported.
      //Export all types derived from IGreetings
       .SelectConstructor(cInfo => cInfo[0]) // this selects first constructor
      //Import types derived from IGreetings
      var v = container.GetExportedValues<IGreetings>();
    3. ForTypesMatching(Predicate predicate): selects types that match a Boolean selector. This is the most flexible means of selection. In the code below, you can see how the type name matching "Greetings" is exported and imported:
      //Export types matching
      regisBuilder.ForTypesMatching(x => x.Name.Equals("HomeGreetings")).Export();
      //import types 
      var greetings = container.GetExportedValue<HomeGreetings>();
  2. Finer-Grained Control Over Lifetime

    ExportFactory improves granularity by allowing developers to create new instances of dependencies and control the lifetimes of the parts.

    ExportFactory<t> can be exported which actually exports the type T, but it doesn’t create instance. Instance of the type will get created when it is accessed with method ExportCreator<t>.CreateExport().

    The return value of ExportCreator<t>.CreateExport() is a ExportLifetimeContext<t>. ExportLifetimeContext<t> has a property called value that contains instance of the type T. ExportLifetimeContext<t> also provides implementation of iDisposable, so instance can be cleaned when it is not required. In the code below, you can see how the ExportFactory<t> is used to export the type and create instance by calling CreateExport() method.

    //Export factory class
    public class ExportFactoryExample
            ExportFactory<Greetings> _factory;
            public ExportFactoryExample(ExportFactory<Greetings> factory)
                _factory = factory;
            public string Greeting(string name)
                using (var instance = _factory.CreateExport())
                    return instance.Value.Greet(name);
    // export the ExportFactoryExample type
    //import the ExportFactoryExample type
    var exportType = container.GetExportedValue<ExportFactoryExample>();
    //CreateExport() method will be called on call of 
    //Greeting method of ExportFactoryExample class

    ExportFactory v/s Lazy objects: The difference between ExportFactory and a Lazy object is that with the Lazy class, you can only create a single instance of the object. The ExportFactory is a class that allows you to request a new instance of the type of object whenever you feel like it.

  3. Diagnostics improvements: Two major improvements have been made to diagnostics.
    • CompositionOptions.DisableSilentRejection parts with missing dependencies are identified and excluded from composition, which makes diagnostics hard in many cases. Specifying CompositionOptions.DisableSilentRejection while constructing a CompositionContainer will cause exceptions to be thrown when any composition problem occurs.
      container = new CompositionContainer
      			(agrCatelog, CompositionOptions.DisableSilentRejection);
    • Better exception messages MEF2 improves the way exception messages are formatted, presenting the most important information up-front.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Milan Raval
Technical Lead IGATE
India India
Programming Passion: C#, WPF, WCF

You may also be interested in...

Comments and Discussions

GeneralMy vote of 1 Pin
John Simmons / outlaw programmer24-Jun-14 9:04
memberJohn Simmons / outlaw programmer24-Jun-14 9:04 
GeneralRe: My vote of 1 Pin
Milan Raval24-Jun-14 10:53
memberMilan Raval24-Jun-14 10:53 
GeneralMy vote of 5 Pin
Safronov Eugen18-Apr-13 4:39
memberSafronov Eugen18-Apr-13 4:39 
GeneralMy vote of 4 Pin
dmihailescu19-Mar-13 4:01
memberdmihailescu19-Mar-13 4:01 
Questionhow about separate assembly for DailyGreetings? Pin
Neeraj.Soni14-Mar-13 3:19
memberNeeraj.Soni14-Mar-13 3:19 
QuestionUmmm... Pin
PIEBALDconsult27-Nov-12 9:47
memberPIEBALDconsult27-Nov-12 9:47 
AnswerRe: Ummm... Pin
Amrykid27-Nov-12 11:50
memberAmrykid27-Nov-12 11:50 
AnswerRe: Ummm... Pin
Milan Raval27-Nov-12 13:54
memberMilan Raval27-Nov-12 13:54 
GeneralRe: Ummm... Pin
Mike Hankey27-Nov-12 14:02
memberMike Hankey27-Nov-12 14:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151126.1 | Last Updated 28 Nov 2012
Article Copyright 2012 by Milan Raval
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid