gpt4 book ai didi

c# - 重复导出

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:05 25 4
gpt4 key购买 nike

我一直在试验 MEF,我注意到我偶尔会得到重复的导出。我创建了这个简化示例:

我已经创建了以下接口(interface)和元数据的属性:

public interface IItemInterface
{
string Name { get; }
}

public interface IItemMetadata
{
string TypeOf { get; }
}

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)]
public class ItemTypeAttribute : ExportAttribute, IItemMetadata
{
public ItemTypeAttribute(string typeOf)
{
TypeOf = typeOf;
}

public string TypeOf { get; set; }
}

然后我创建了以下导出:

public class ExportGen : IItemInterface
{
public ExportGen(string name)
{
Name = name;
}

public string Name
{
get;
set;
}
}

[Export(typeof(IItemInterface))]
[ItemType("1")]
public class Export1 : ExportGen
{
public Export1()
: base("Export 1")
{ }
}


public class ExportGenerator
{
[Export(typeof(IItemInterface))]
[ExportMetadata("TypeOf", "2")]
public IItemInterface Export2
{
get
{
return new ExportGen("Export 2");
}
}

[Export(typeof(IItemInterface))]
[ItemType("3")]
public IItemInterface Export3
{
get
{
return new ExportGen("Export 3");
}
}
}

执行这段代码:

AggregateCatalog catalog = new AggregateCatalog();
CompositionContainer container = new CompositionContainer(catalog);
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly().CodeBase));

var exports = container.GetExports<IItemInterface, IItemMetadata>();

foreach (var export in exports)
{
Console.WriteLine(String.Format("Type: {0} Name: {1}", export.Metadata.TypeOf, export.Value.Name));
}

这个输出:

Type: 1 Name: Export 1Type: 2 Name: Export 2Type: 3 Name: Export 3Type: 3 Name: Export 3

当我调用 GetExports() 时,我得到了 Export3 的副本,导出 1 和 2 没有重复。 (请注意,当我使用 ItemTypeAttribute 时,我得到了副本。)

如果我删除类型 1 和 2,并调用“GetExport”,它会抛出异常,因为有超过 1 个导出。

Google 搜索结果为 single blog一年前的帖子,但没有解决或跟进

我是不是做错了什么,或者可能遗漏了什么愚蠢的东西?

(所有这些都是使用 VS2010 和 .NET 4.0。)

最佳答案

ItemTypeAttribute 的构造函数更改为:

public ItemTypeAttribute(string typeOf)
: base(typeof(IItemInterface))
{
TypeOf = typeOf;
}

并删除

[Export(typeof(IItemInterface))]

因为您的自定义属性派生自 ExportAttribute。这解释了您的双重导出。

指南可在 MEF's Documentation 的“使用自定义导出属性”部分找到在 CodePlex 中。

关于c# - 重复导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13424913/

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