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

  • image1452_thumb.png
    Javascript to Dart Translator

      Dart, a Google Javascript alternative was presented a few months ago and the web developer scene are a little bit unsure about the usability of Dart. To declare the language Google has translated the Javascript basics into Dart. The result is this “Translator”. In my opinion the name doesn’t find that well because it’s ...

  • image1366-570x194.png
    Twitter Bootstrap as UI-kit

      HTML and CSS are not foreign words for me but I regret, I’m not a Web designer – I see myself as a webdeveloper. But at least a dressy side is a must. But thank good there are some ready “Systems”. Twitter Bootstrap Twitter Bootstrap is a Toolkit for every kind of Web applications. ...

  • image1441.png
    Fix: the value ‚x‘ is not valid for Foo in ASP.NET MVC

      To get files into the MVC Controller Modelbinding from MVC is a clever method. But in fact it is a little bit complicated to set the error message if the connection failed. Example: public class RegisterModel { ... [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; } [Required] [Display(Name = ...

  • You Tube API – recall Video Meta files with .NET

      A loooong time ago I’ve blogged about how to access to You Tube with the Google Data APIs. After all that time there are several new ways how to recall files. Google offers You Tube a “simple” surface. If you prefer to do low-Level HTTP calls it is also possible. Aim: I want the ...

  • image1426-570x194.png
    MacBook Pro for .NET Developer – useful ore just pretty?

      I own a MacBook Pro (from 2010) for about a year now and because I’ve used to think about this Question since I have it, I’m going to blog about my experience now. My Notebook Configurations MacBook Pro April 2010 - 2,66 Intel Core i7 - 8GB RAM - 15’’ Glossy Display - Intel ...

Support us