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)), PartCreationPolicy(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;
}
}
}
It seems to be an issue with ContainerBuilder. I tried alternate approach with CompositionContainer and it worked without hurdles. Pasting the code snippet for modified methods.
public PartsManager()
{
ConstructContainer();
}
private void ConstructContainer()
{
var catalog = new DirectoryCatalog(@"C:\plugins\");
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
container.SatisfyImportsOnce(this);
}