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

No comments:

Post a Comment