Example for ExportFactory<T> needed

May 4, 2010 at 7:27 AM
Edited May 4, 2010 at 2:15 PM

Hello,

can anybody please help me out with a sample for using ExportFactory<T>?

This is what I have so far:

 

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace MEFTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Run();
        }

        private void Run()
        {
            Compose();
            GetMessageSender();
            Console.ReadLine();

        }

        private void Compose()
        {
            AssemblyCatalog catalog = new AssemblyCatalog(typeof(Program).Assembly);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        private void GetMessageSender()
        {
            MessageSenderController messageSenderController = new MessageSenderController();
            IMessageSender messageSender = messageSenderController.CreateMessageSender();
        }
    }

    public class MessageSenderController
    {
        [Import]
        public ExportFactory<IMessageSender> MessageSenderFactory { get; set; }

        public IMessageSender CreateMessageSender()
        {
            return this.MessageSenderFactory.CreateExport().Value;
        }
    }

    public interface IMessageSender
    {
        void Send(string message);
    }

    [Export(typeof(IMessageSender))]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
    public class EmailSender : IMessageSender
    {
        public void Send(string message)
        {
            Console.WriteLine(message);
        }
    }

    [Export(typeof(IMessageSender))]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
    public class TCPSender : IMessageSender
    {
        public void Send(string message)
        {
            Console.WriteLine(message);
        }
    }
}

 

The MessageSenderFactory is always null but there are no composition errors.

Any help is appreciated - thanks!

May 4, 2010 at 5:08 PM

Well, you're doing a few things wrong.

 

1. the call to container.ComposeParts(this); is no-op since you dont have any imports in the Program class.

2. you're instantiating MessageSenderController yourself instead of using the MEF container. Therefore no imports will be satisfied, and the member will be null.

3. you should keep a ref to the container for the lifetime of your app/components.