using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; [Import] ILogger logger; public class MyApp { public MyApp() { var container = new CompositionContainer(); container.ComposeParts(this); logger.Log("Application started"); } }
using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; [Export("calculator", typeof(ICalculator))] public class MultiplicationCalculator : ICalculator { public int Calculate(int a, int b) { return a * b; } } public interface ICalculator { int Calculate(int a, int b); } public class MyApp { public MyApp() { var container = new CompositionContainer(); container.ComposeParts(this); var calculator = container.GetExportedValueHere, we define an interface ICalculator that specifies the API for our calculator class. We then define a class MultiplicationCalculator that implements ICalculator and is marked with the [Export] attribute. This tells MEF that this class can be used to satisfy [Import] attributes that look for an implementation of ICalculator. In MyApp, we create an instance of CompositionContainer and call ComposeParts() with the current object. We then use the GetExportedValue method of the container to get an instance of ICalculator that is marked with the identifier "calculator". We call Calculate() on this instance to perform multiplication and write the result to the console. Package library: The CompositionContainer class is part of the System.ComponentModel.Composition package library.("calculator"); int result = calculator.Calculate(3, 5); Console.WriteLine(result); } }