【问题标题】:Duplicate Exports重复导出
【发布时间】:2012-11-16 21:48:47
【问题描述】:

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

我创建了以下接口,以及元数据的属性:

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));
}

这个输出:

类型:1 名称:出口 1 类型:2 名称:出口 2 类型:3 名称:出口 3 类型:3 名称:出口 3

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

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

谷歌搜索得到了一年前的 single blog 帖子,但没有解决方案或后续行动

我在这里做错了什么,或者可能错过了一些愚蠢的事情吗?

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

【问题讨论】:

    标签: c# mef


    【解决方案1】:

    ItemTypeAttribute的构造函数改为:

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

    并删除

    [Export(typeof(IItemInterface))]
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-05
      • 2018-03-03
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 2015-02-02
      • 2017-12-30
      • 2011-10-31
      相关资源
      最近更新 更多