[英]MEF ImportingConstructor ImportMany with Metadata
I'm using MEF to import many (with metadata) in a constructor.我正在使用 MEF 在构造函数中导入许多(带有元数据)。 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 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 ISimpleMetadata.cs
public interface ISimpleMetadata
{
string Name { get; }
}
Catalog.cs目录.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.代码运行,但我没有得到任何 catalog.imports。 When I look at the catalog there's 1 Catalog exported and an AbsractImportMe.当我查看目录时,有 1 个导出的目录和一个 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.所以我想我在元数据方面犯了一个错误。
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{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.