Initializing ExportFactory using MEF
- by Riz
Scenario
Application has multiple parts.
Each part is in separate dll and implements interface IFoo
All such dlls are present in same directory (plugins)
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;
}
}
}