CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

MEF Factory

572 Views
Copy Code Show/Hide Line Numbers
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
 
namespace MEFFactory
{
    public interface IMessage
    {
        string Text { get; set; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Run();
        }
 
        private void Run()
        {
            var messages = new MessageRepository();
 
            CompositionFactory.ComposeObject(messages);
 
            foreach(var message in messages.Messages)
            {
                Console.WriteLine(message.Text);
            }
 
            Console.ReadKey();
        }
    }
 
    class CompositionFactory
    {
        public static void ComposeObject<T>(T obj)
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);
            
            container.ComposeParts(obj);
        }
    }
 
    class MessageRepository
    {
        [ImportMany("Messages", typeof(IMessage))]
        public IEnumerable<IMessage> Messages { get; set; }
    }
 
    [Export("Messages", typeof(IMessage))]
    class Message1 : IMessage
    {
        public string Text { get; set; }
 
        public Message1() 
        {
            Text = "One"; 
        }
    }
 
    [Export("Messages", typeof(IMessage))]
    class Message2 : IMessage
    {
        public string Text { get; set; }
 
        public Message2()
        {
            Text = "Two";
        }
    }
 
}
by JamesEggers
  April 20, 2010 @ 2:45pm
Tags:
Description:
Just a throw together console app that composes a separate class using a factory pattern to handle the MEF composition.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate