Initializing ExportFactory using MEF

Posted by Riz on Stack Overflow See other posts from Stack Overflow or by Riz
Published on 2014-06-10T03:19:33Z Indexed on 2014/06/10 3:24 UTC
Read the original article Hit count: 124

Filed under:
|
  1. Scenario
    1. Application has multiple parts.
    2. Each part is in separate dll and implements interface IFoo
    3. All such dlls are present in same directory (plugins)
    4. The application can instantiate multiple instances of each part

Below is the code snippet for the interfaces, part(export) and the import. The problem I am running into is, the "factories" object is initialized with empty list.

However, if I try container.Resolve(typeof(IEnumerable< IFoo >)) I do get object with the part. But that doesn't serve my purpose (point 4). Can anyone point what I am doing wrong here?

public interface IFoo
{
    string Name { get; }
}

public interface IFooMeta
{
    string CompType { get; }
}

Implementation of IFoo in separate Dll

[ExportMetadata("CompType", "Foo1")]
[Export(typeof(IFoo), RequiredCreationPolicy = CreationPolicy.NonShared))]
public class Foo1 : IFoo
{
    public string Name
    {
        get { return this.GetType().ToString(); }
    }
}

Main application that loads all the parts and instantiate them as needed

class PartsManager
    {
        [ImportMany]
        private IEnumerable<ExportFactory<IFoo, IFooMeta>> factories;

        public PartsManager()
        {
            IContainer container = ConstructContainer();    
            factories = (IEnumerable<ExportFactory<IFoo, IFooMeta>>)
                   container.Resolve(typeof(IEnumerable<ExportFactory<IFoo, IFooMeta>>));    
        }    

        private static IContainer ConstructContainer()
        {
            var catalog = new DirectoryCatalog(@"C:\plugins\");
            var builder = new ContainerBuilder();         
            builder.RegisterComposablePartCatalog(catalog);

            return builder.Build();
        }

        public IFoo GetPart(string compType)
        {
            var matchingFactory = factories.FirstOrDefault(
                x => x.Metadata.CompType == compType);
            if (factories == null)
            {
                return null; 
            }
            else
            {
                IFoo foo = matchingFactory.CreateExport().Value;
                return foo;
            }
        }
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about MEF