skip to the main content area of this page
Patterns and Practices

 

Managed Extensibility Framework Tutorial - MEF


Brad Abrams has an introductory tutorial on the Managed Extensibility Framework. He shows how to use the AttributedAssemblyPartCatalog and CompositionContainer in a Console Application to import and export string types in a simple console application that prints messages to the Console. I recommend checking out Brad's post for a good tutorial on the Managed Extensibility Framework.

For kicks, I couldn't resist downloading the MEF and creating a Managed Extensibility Framework Tutorial of my own. Shown below I created a Console Application that uses the Import ( System.ComponentModel.Composition.ImportAttribute ) and Export ( System.ComponentModel.Composition.ExportAttribute ) Attributes to import a ConsoleLogger of type ILogger into the Application Class to be used for logging.

Feels like dependency injection to me without the use of an explicit Inversion of Control / Dependency Injection Tool.

 

using System;

using System.ComponentModel.Composition;

 

namespace MefSample

{

    class Program

    {

        static void Main(string[] args)

        {

            Application app = new Application();

            app.Run();

        }

    }

 

    public class Application

    {

        [Import]

        public ILogger Logger { get; set; }

 

        public void Run()

        {

            var catalog = new AttributedAssemblyPartCatalog

                (System.Reflection.Assembly.GetExecutingAssembly());

            var container = new CompositionContainer

                (catalog.CreateResolver());

            container.AddPart(this);

            container.Compose();

 

            Logger.Write("Hello World");

            Console.ReadLine();

        }

    }

 

    public interface ILogger

    {

        void Write(string message);

    }

 

    [Export(typeof(ILogger))]

    public class ConsoleLogger : ILogger

    {

        public void Write(string message)

        {

            Console.WriteLine(message);

        }

    }

}

 

Hope the MEF Tutorial helps.


Tags: ManagedExtensibilityFramework


Topics



 

Popular Tags



Recent Links