Tuesday, 1 May 2012

C# Addin framework, MEF Example (Managed Extensibility Framework)

Example of using MEF to dynamically load calculator object.

Create .Net 4.0 solution with the following projects (MEFExample is Console others are Libraries)
Add Reference to System.ComponentModel.Composition to Library projects.

image

public interface ICalculator
{
    string Name { get; }
    int Calculate(int a, int b);
}
public class CalculatorManager
{
    [ImportMany(typeof(ICalculator))]
    private IEnumerable<ICalculator> _calculators;
    public IEnumerable<ICalculator> GetCalculators()
    {
        var catalog = new AggregateCatalog();            
        catalog.Catalogs.Add(new DirectoryCatalog(@".\extensions\"));
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
        Console.WriteLine("Found {0} Calculators", _calculators.Count());
        return _calculators;
    }
}
[Export(typeof(ICalculator))]
public class CalculatorAdd : ICalculator
{        
    public string Name
    {
        get { return "Mul a & b"; }
    }
    public int Calculate(int a, int b)
    {
        return a * b;
    }        
}
[Export(typeof(ICalculator))]
public class Calculator : ICalculator
{
    public string Name
    {
        get { return "Add a & b"; }
    }
    public int Calculate(int a, int b)
    {
        return a + b;
    }
}
public class MEFExample
{
    public static void Main(string[] args)
    {
        var calculators = new CalculatorManager().GetCalculators();
        foreach (var calculator in calculators)
        {
            Console.WriteLine("Calculator: {0}(1,2): {1}", calculator.Name, calculator.Calculate(1, 2));
        }
    }
}
To test the code copy the compiled dlls to new folder with extensions subfolder.
/extensions
/extensions/MEFLib1.dll
/extensions/MEFLib2.dll
/MEFExample.exe
/MEFLib.dll

and run MEFExample.exe

image

No comments:

Post a Comment