Share via


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. }

Comments

  • Anonymous
    December 28, 2011
    sample for  external class using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Reflection; namespace ClassLibrary1 {    public class ExternalProvider    {        [Export("ProviderName")]        public string Name        {            get            {                return "Spider";            }        }     } } using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Reflection; using ClassLibrary1; class Program {    static void Main()    {        new Program().Run();    }    [Import("ProviderName")]    string providerName;    void Run()    {        Assembly SampleAssembly;        // Instantiate a target object.        ExternalProvider _ExternalProvider = new ExternalProvider();        Type Type1;        // Set the Type instance to the target class type.        Type1 = _ExternalProvider.GetType();        // Instantiate an Assembly class to the assembly housing the Integer type.          SampleAssembly = Assembly.GetAssembly(_ExternalProvider.GetType());        // Gets the location of the assembly using file: protocol.        new CompositionContainer(new AssemblyCatalog(SampleAssembly)).ComposeParts(this);        Console.WriteLine(this.providerName);    } }

  • Anonymous
    October 25, 2014
    Can you comment your code more extensively? Thanks in advance.