MEF (Managed Extensibility Framework) Is it a real DI container? - A quick overview



The 3 core areas which distinguish a Dependency Injection (DI) container are:

  • Object composition
  • Object lifetime management
  • Interception

Castle Windsor, Unity, Ninject are some of the DI container which exhibit these capabilities. However, most of the striking question with MEF is what really is MEF, is it a DI container and what are its capabilities? So here I have tried to give a quick summary of MEF's capabilities.

MEF is typically used for creating extensible applications based on class discovery (service location). It is the only composition technology shipped and supported by Microsoft. MEF is not a real Dependency Injection (DI) container but a extensibility framework as the name suggests.

MEF is part of the .NET framework. The relevant classes are located under System.ComponentModel.Composition namespace.

MEF features include:

  • Auto-resolution of implicit dependencies and composition. 
  • Until 4.0 the dependency resolution was achieved using the Import and Export attributes. However, the 4.5 release supports convention based programming too.
  • Manage object lifetimes using PartCreationPolicy attribute. The available options are: CreationPolicy.Shared, CreationPolicy.NonShared, CreationPolicy.Any). By default the object lifetime is Singleton i.e. shared. 
  • Class discovery by creation of catalogs. The catalogs provided are  AggregateCatalog, AssemblyCatalog, DirectoryCatalog, TypeCatalog. 
  • CompositionContainer, a DI container that  takes in the catalog to resolve dependencies. 
  • Support for Constructor and Property injection.
  • Lazy initialization of classes using Lazy
  • Few other attributes like ImportMany (for supporting hookup of collection of classes with same interface) and ImportingConstructor (hints MEF on which constructor to use for injection)

What's new in 4.5?

  • Support for generic types
  • Support for convention based programming style
  • Multiple scopes

Brushing up C# features ...



Recently, as a  part of the ASP.NET MVC 4 training I got an opportunity to brush up few C# features.

Lazy
Provides support for lazy initialization i.e. the object is created or instantiated at the last moment or only when it is needed. The value of the object can be accessed using Lazy.Value property.

dynamic keyword
dynamic keyword hints the compiler to skip the compile time type checking and defers the resolution until runtime. This means that the Visual Studio intellisense for the object defined using dynamic keyword will not be available.

dynamic obj = 1;

Expando object
Expando allows creation of an object with members that can be dynamically added and removed at run time. Here's an example:

dynamic person = new ExpandoObject();
person.Name = "nimish bhonsale";
var method = new Action((x)=> Console.Write(x));
person.Write = method;
person.Write(person.Name.ToString());