HowTo: First Steps with MEF (Hello MEF!)

In nearly every application you can install and use plugins (Firefox, Outlook, IE…). With .NET 4.0 you get a new feature to create extensible applications called "Managed Extensibility Framework" in short "MEF". You can today play with a preview of this upcoming framework.
Microsoft itself will use it in Visual Studio 2010 (take a look at the PDC Keynote from Scott Guthrie). A very nice demo of MEF was in the PDC session of Scott Hanselman and his "BabySmash". But there are a lot of other great MEF PDC Sessions.

Addins? .NET? System.Addin? 
The "System.AddIn" Namespace was introduced in .NET 3.5, but it was very hard to create addins. But MEF and System.AddIn should play well together.

What´s needed to play with MEF?
Everything you needed to start you can download at the Codeplex Site. Just download the newest release and copy the 2 DLLs in your project directory (Disclaimer- it´s still in development, everything might be changed until the release).

Hello World! Hallo Welt! Hello MEF! – Preparation

Projectstructure:

image

We have a simple service interface called "IHelloService":

    public interface IHelloService
    {
        string GetHelloMessage();
    }

In the HelloMEF.English / German Project we have the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HelloMEF.App;
using System.ComponentModel.Composition;

namespace HelloMEF.English
{
    [Export(typeof(IHelloService))]
    public class EnglishHelloService : IHelloService
    {
        public string GetHelloMessage()
        {
            return "Hello World!";
        }
    }
}

Important for MEF is the "Export" attribut from the "System.ComponentModel.Composite" (MEF) Namespace.

Export means: This is a "IHelloService" plugin.

Both projects need only the reference to the HelloMEF.App because of the IHelloService interface.

The HelloMEF.App doesn´t know anything about these projects!

Plugin dictionary

Your application needs to know where plugins are placed, that´s why we create a "PlugIns" dictionary:

image

HelloMEF.App – HelloProgram:

    public class HelloProgram
    {
        [Import(typeof(IHelloService))]
        public List<IHelloService> Services { get; set; }

        public HelloProgram()
        {
	...
        }

        public void WriteHelloGreetings()
        {
            Console.WriteLine();
            Console.WriteLine("Writing Greetings...");

            foreach (IHelloService srv in Services)
            {
                Console.WriteLine(srv.GetHelloMessage());
            }

            Console.WriteLine("... powered by MEF");
        }
    }

Inside the "HelloProgram" class is a "IHelloServices" list, which is decorated with the "Import" attribute from the MEF namespace.

Import means: I took everything of type IHelloService.

The "WriteHelloGreeting" just iterate over the services list and write the message to the console.

HelloMEF.App – search & found plugins:

        public HelloProgram()
        {
            this.Services = new List<IHelloService>();

            if (!Directory.Exists("PlugIns"))
            {
                Directory.CreateDirectory("PlugIns");
            }

            AggregatingComposablePartCatalog catalog = new AggregatingComposablePartCatalog();
            catalog.Catalogs.Add(new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()));
            catalog.Catalogs.Add(new DirectoryPartCatalog("PlugIns"));

            CompositionContainer container = new CompositionContainer(catalog.CreateResolver());
            container.AddPart(this);
            container.Compose();
        }

At first we search for the "PluginIns" directory and create it if it it´s necessary. Now – pure MEF action:

Plugins are manged with parts and catalogs. We tell our catalog to search for plugins in this assembly:

            catalog.Catalogs.Add(new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()));

… and to look at this directory:

            catalog.Catalogs.Add(new DirectoryPartCatalog("PlugIns"));

We can also observe the directory, to add plugins while the application is running:

image

Through the container we tell MEF that here is a plugin interface (the list with the import attribute) and start the "compose" process.

HelloMEF.App – Plugins inside the assembly:

namespace HelloMEF.App
{
    public class HelloProgram
    {
	...
    }

    [Export(typeof(IHelloService))]
    public class MEFHelloService : IHelloService
    {
	...
    }

}

The plugins could be placed inside the assembly. MEF find these plugins through this catalog: "AttributeAssemblyPartCatalog"

The result:

image

 [ Download Source Code ]

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by Code Inside Team

Currently there is no additional info about this author.

3 Responses

  1. very nice tutorial! keep on the good work!

    Reply

Comment on this post

Recent Posts

  • Windows Phone Fonts & what if Visual Studio lies

    Today I was confronted with a little Problem: my Windows Phone App refused to show me the Font I choose – also other thinks didn’t work. Although the Visual Studio Designer did show the Fonts: Unfortunately there isn’t much left in the Emulator: Reason for this: Windows Phone doesn’t include all the typos Windows does ...

  • Json-Online-Tools: Viewer & Json2Csharp generator

      Wherever APIs are mentioned the JSON format I not far away. Since I’m using two tools regularly I would like to introduce you to them. JSON Viewer If you only see the JSON-Text you are usually not able to see the structure. With the help of JSON Viewer you can have an easy overview: ...

  • Windows Phone SDK & „System“-Icons

      Although the Metro Design focuses a lot on Typography Icons are still quite important. If you install Windows Phone SDK you will receive 36 Icons. You can find them here: C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons Unfortunately many Icons you might know from the common applications are not integrated. Pedro Lamas extracted 99 additional Icons ...

  • image1830-570x194.png
    How can I figure out if my ADFS 2.0 works?

      I was working with ADFS 2.0 (“Active Directory Federation Services”) for a while when this simple question crossed my mind: How can I figure out if the connection between ADFS and AD “works”? Here is a simple test… What is ADFS? If you need some “position of trusts” beneath the AD-boarders you choose an ...

  • Subdomain vs. Subdirectory

      Better blog.mydomain.com or mydomain.com/blog? Good question! If got asked this question again via Twitter on the weekend so therefore I decide to share my experiences:   Choose a subdomain, if…. - You plan to offer “different services” which are “logical separated” on one domain - You are able to influence the subdomains without much ...

Support us