Reputation: 1535
I'm trying to write an ExportProvider that exports conditionally based on metadata found on the Export and on the Import. Exports metadata is easy:
[Export(typeof(ITestExport))]
[TestExportMetadata(MetadataStr = "A", MetadataInt = 2)]
public class TestExportClass1 : ITestExport
{
}
Examining the export metadata and providing an export based on it simple. What I want to do for imports is something similar, maybe like this:
public class TestImportClass1
{
[Import(typeof(ITestExport))]
[TestImportMetadata(MetadataStr = "A", MetadataInt = 2)]
ITestExport MyExportedValue { get; set; }
}
The actual signature of TestImportMetadata is not significant here except that I'd like to provide some sort of metadata to the import and be able to reference that when it comes time to satisfy that import. Unfortunately there seems to be no designed equivalent process for applying metadata to an import like there is to an export.
The ExportProvider base class provides the abstract method:
protected abstract IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition);
I would think the ImportDefinition provided to this method would give me some sort of access, directly or indirectly, to my metadata or at least to the ImportAttribute itself, but it doesn't seem to.
If this simply isn't possible the way I've described it, can anyone think of an alternate method to providing and accessing import metadata when it comes to satisfy an import?
Upvotes: 2
Views: 1825
Reputation: 31767
If you are targeting .NET 4.5, you can use the Microsoft.Composition NuGet package instead of the MEF version that is 'in the box'. This has some functional differences and isn't a drop-in replacement, but one added capability is the ImportMetadataConstraint
attribute:
public class TestImportClass1
{
[Import(typeof(ITestExport))]
[ImportMetadataConstraint("MetadataStr", "A")]
[ImportMetadataConstraint("MetadataInt", 2)]
public ITestExport MyExportedValue { get; set; }
}
This works with custom metadata attributes as well, so you could alternatively write:
public class TestImportClass1
{
[Import(typeof(ITestExport))]
[TestExportMetadata(MetadataStr = "A", MetadataInt = 2)]
public ITestExport MyExportedValue { get; set; }
}
(Note that the properties need to be public in order to be used as imports here.)
Upvotes: 2