C# 重复出口

C# 重复出口,c#,mef,C#,Mef,我一直在试验MEF,我注意到我偶尔会得到重复的输出。我创建了这个简化的示例: 我已经为元数据创建了以下接口和属性: public interface IItemInterface { string Name { get; } } public interface IItemMetadata { string TypeOf { get; } } [MetadataAttribute] [AttributeUsage(AttributeTargets.Class | Attrib

我一直在试验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));
}
AggregateCatalog catalog=new AggregateCatalog();
CompositionContainer=新的CompositionContainer(目录);
catalog.Catalogs.Add(新的AssemblyCatalog(Assembly.getExecutionGassembly().CodeBase));
var exports=container.GetExports();
foreach(导出中的var导出)
{
WriteLine(String.Format(“类型:{0}名称:{1}”,export.Metadata.TypeOf,export.Value.Name));
}
这将产生:

Type: 1 Name: Export 1 Type: 2 Name: Export 2 Type: 3 Name: Export 3 Type: 3 Name: Export 3 类型:1名称:导出1 类型:2名称:导出2 类型:3名称:导出3 类型:3名称:导出3 当我调用GetExports()时,我得到了Export3的一个副本,而Export1和Export2没有重复。(请注意,当我使用ItemTypeAttribute时,会得到副本。)

如果我删除类型1和2,并调用“GetExport”,它会抛出一个异常,因为存在多个导出

一次谷歌搜索产生了一个一年前的帖子,但没有解决方案或后续行动

我是做错了什么,还是错过了一些愚蠢的事情


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

ItemTypeAttribute的构造函数更改为:

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

[Export(typeof(IItemInterface))]
因为您的自定义属性是从
ExportAttribute
派生的。这解释了你的双重出口

可以在CodePlex中的“使用自定义导出属性”部分找到指导原则