Reputation: 431
I'm using MEF to import many (with metadata) in a constructor. I've followed a video tutorial to try to mimic it but so far it's not quite working. Briefly, I have re-named some things and summarized, but:
AbstractImportMe.cs
[InheritedExport(typeof(AbstractImportMe))]
public abstract class AbstractImportMe{
}
ImportMe.cs
[SimpleMetadata("Name")]
class ImportMe : AbstractImportMe
{
}
SimpleMetadata.cs
[MetadataAttribute]
public class SimpleMetadata : Attribute,ISimpleMetadata
{
public string Name { get; private set; }
public SimpleMetadata(String Name)
{
this.Name = Name;
}
}
ISimpleMetadata.cs
public interface ISimpleMetadata
{
string Name { get; }
}
Catalog.cs
[Export]
public class Catalog
{
public IEnumerable<Lazy<AbstractImportMe, ISimpleMetadata>> imports = null;
[ImportingConstructor]
/*this runs but the imports field has 0 parts*/
public Catalog([ImportMany] IEnumerable<Lazy<AbstractImportMe, ISimpleMetadata>> imports)
{
this.imports = imports;
}
/* this code works, but it lacks metadata
public IEnumerable<AbstractImportMe> imports= null;
[ImportingConstructor]
public Catalog([ImportMany] IEnumerable<AbstractImportMe> imports)
{
this.imports = imports;
}
*/
}
Then I call this code:
AggregateCatalog catalog = new AggregateCatalog(newAssemblyCatalog(Assembly.GetEntryAssembly().Location));
CompositionContainer container = new CompositionContainer(catalog);
Catalog catalog = container.GetExportedValue<Catalog>();
The code runs, but I don't get any catalog.imports. When I look at the catalog there's 1 Catalog exported and an AbsractImportMe.
As pointed out before, when I exclude the metadata from the import it works fine. So I think I have made a mistake somewhere in regards to the metadata.
Upvotes: 3
Views: 2348
Reputation: 431
I found the issue, I needed to add a metadata tag to the base class to keep the signature consistent. Since the export is inherited it keeps the signature.
[InheritedExport(typeof(AbstractImportMe))]
[SimpleMetadata("Abstract")]
public abstract class AbstractImportMe{
}
Upvotes: 2