Pages

Wednesday, November 27, 2013

MEF Simple Application in C#

I believe the best way to learn something new is to learn by simple and easy to understand example. Once you got the principles you can always proceed to more complex stuff. So today I'll show a simple example of MEF that will give you the basics.

Managed Extensibility Framework (MEF) is a component of .NET 4 and it allows to developer to build extensible applications. Imagine situation when you have some application and you know that in the future you will want to add more features to it, but you don't know exactly what and when they will be added, or may be you want another developer to develop new feature and integrate it seamlessly into the main application. So it looks like we need some module structured application here, right? And this is exactly what MEF provides.
Now to our sample application. When user starts it he asked to enter a string and a command (name of operation) he want to apply on that string. Once it's done the program will print the result string. So every operation we want to be a separate module. Enough bla bla! Let's see the code! :)

First, the Core class which is a part of the main application. Core class concentrates and launches all available extensions:
public interface ICore
{
    String PerformOperations(string data, string command);
}

[Export(typeof(ICore))]
public class Core : ICore
{
    [ImportMany]
    private IEnumerable<Lazy<IOperation, IOperationCommand>> _operations;

    public string PerformOperations(string data, string command)
    {
        foreach (Lazy<IOperation, IOperationCommand> i in _operations)
        {
            if (i.Metadata.Command.Equals(command))
                return i.Value.Operate(data);
        }
        return "Unrecognized operation";
    }
}