Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MEF ImportingConstructor ImportMany with Metadata

Tags:

c#

metadata

mef

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.

like image 933
pcaston2 Avatar asked Mar 11 '26 16:03

pcaston2


1 Answers

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{

} 
like image 184
pcaston2 Avatar answered Mar 14 '26 06:03

pcaston2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!