我正在使用MEF在构造函数中导入许多(带元数据)。我已经按照视频教程试图模仿它,但到目前为止它并不是很有效。简而言之,我重新命名了一些内容并进行了总结,但是:
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;
}
*/
}
然后我调用此代码:
AggregateCatalog catalog = new AggregateCatalog(newAssemblyCatalog(Assembly.GetEntryAssembly().Location));
CompositionContainer container = new CompositionContainer(catalog);
Catalog catalog = container.GetExportedValue<Catalog>();
代码运行,但我没有得到任何catalog.imports。当我查看目录时,会导出1个目录和一个AbsractImportMe。
如前所述,当我从导入中排除元数据时,它可以正常工作。所以我认为我在元数据方面犯了一个错误。
答案 0 :(得分:1)
我发现了这个问题,我需要在基类中添加元数据标签以保持签名的一致性。由于导出是继承的,因此保留了签名。
[InheritedExport(typeof(AbstractImportMe))]
[SimpleMetadata("Abstract")]
public abstract class AbstractImportMe{
}