gpt4 book ai didi

c# - MEF ImportingConstructor ImportMany 与元数据

转载 作者:行者123 更新时间:2023-12-02 03:27:56 51 4
gpt4 key购买 nike

我正在使用 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; }
}

目录.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。

如前所述,当我从导入中排除元数据时,它工作正常。所以我认为我在元数据方面犯了一个错误。

最佳答案

我发现了问题,我需要向基类添加元数据标记以保持签名一致。由于导出是继承的,因此它保留了签名。

[InheritedExport(typeof(AbstractImportMe))] 
[SimpleMetadata("Abstract")]
public abstract class AbstractImportMe{

}

关于c# - MEF ImportingConstructor ImportMany 与元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29284913/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com