My Blog

Export methods using MEF

by lupok on mercoledì 16 gennaio 2013 17:28
Occorre creare una classe che dispone di uno o più metodi:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
 
namespace MefExportMethods
{
   public class Methods
   {
      [Export("methods")]
      public String Method1()
      {
         return "this is method 1";
      }
 
      [Export("methods")]
      public String Method2()
      {
         return "this is method 2";
      }
   }
}
Se vogliamo importare i metodi esportati all'interno di un'unica lista è necessario che la firma dei metodi sia identica per tutti. Per importare i metodi esportati dalla classe riportata sopra è sufficiente definire una proprietà con la seguente firma:
      [ImportMany("methods")]
      public IEnumerable<Func<String>> Methods { getset; }
Da notare che i tipi presenti nel template Func devono corrispondere alla firma dei metodi esportati. Di seguito è presente il codice che mostra come è possibile richiamare i metodi importati:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;
 
namespace MefExportMethods
{
   class Program
   {
      private CompositionContainer _container;
 
#pragma warning disable 0649
 
      [ImportMany("methods")]
      public IEnumerable<Func<String>> Methods { getset; }
 
#pragma warning restore 0649
 
      private Program()
      {
         //An aggregate catalog that combines multiple catalogs
         var catalog = new AggregateCatalog();
         //Adds all the parts found in the same assembly as the Program class
         catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
 
         //Create the CompositionContainer with the parts in the catalog
         _container = new CompositionContainer(catalog);
 
         //Fill the imports of this object
         try
         {
            this._container.ComposeParts(this);
         }
         catch (CompositionException compositionException)
         {
            Console.WriteLine(compositionException.ToString());
         }
      }
 
      static void Main(string[] args)
      {
         Program p = new Program(); //Composition is performed in the constructor
 
         foreach (var method in p.Methods)
         {
            Console.WriteLine(method());
         }
 
 
         Console.WriteLine("press enter to exit");
         Console.ReadLine();
      }
   }
}


MefExportMethods.zip
		

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags