Mef is Managed Extensibility Framework. That means that with MEF we can easily make plugin system.
To write this article mostly I was using this article.
In this my small example I am going to make one class library, called MefExport, and with that library I will display "hello world" message in console, in separate solution, in order to have separated as much as possible.
Then I will make console application, called MefImport where I will use method from MefExport.
Let's first make console application, which we will call MefExport:
Right click on references -> Add Reference...
Choose System.ComponentModel.Composition
Code for export:
using System; using System.ComponentModel.Composition; namespace MefExport { public interface IHelloWorld { string HelloWorld(); } [Export(typeof(IHelloWorld))] public class MefHelloWorld : IHelloWorld { public string HelloWorld() { return "Hello world"; } } }
After building copy export dll in the lib folder. Change line: catalog.Catalogs.Add(new DirectoryCatalog(@"../../lib")); According to where dll is located.
Import:
using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using MefExport; namespace MefImport { class Program { private CompositionContainer _container; [Import(typeof(IHelloWorld))] private IHelloWorld helloWorld; private Program() { var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly)); catalog.Catalogs.Add(new DirectoryCatalog(@"../../lib")); _container = new CompositionContainer(catalog); try { this._container.ComposeParts(this); } catch (CompositionException compositionException) { Console.WriteLine(compositionException.ToString()); } } static void Main(string[] args) { Program p = new Program(); Console.WriteLine(p.helloWorld.HelloWorld()); Console.ReadKey(); } } }
Example project download from here.