System.ComponentModel.Composition Example

I started playing with the .NET Framework 4.0 composition namespace (also known as MEF) and I want to share the most simple example I could write. The program prints out the providerName field, but the actual value is provided by the ExternalProvider class. The CompositionContainer class is able to wire the ExternalProvider.Name property and the Program.providerName field using the Export and Import attributes.

Add the System.ComponentModel.Composition.dll assembly to your project’s references.

Really simple, I think.

  1. using System;

  2. using System.ComponentModel.Composition;

  3. using System.ComponentModel.Composition.Hosting;

  4. using System.Reflection;

  5. class ExternalProvider {

  6.     [Export("ProviderName")]

  7.     public string Name {

  8.         get {

  9.             return "Spider";

  10.         }

  11.     }

  12. }

  13. class Program {

  14.     static void Main() {

  15.         new Program().Run();

  16.     }

  17.     [Import("ProviderName")]

  18.     string providerName;

  19.     void Run() {

  20.         new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly())).ComposeParts(this);

  21.         Console.WriteLine(this.providerName);

  22.     }

  23. }