MEF ImportMany接口的第一个实现会掩盖以下任何实现

时间:2019-06-24 15:54:45

标签: c# mef

我对MEF插件的概念证明应用程序有疑问。我有一个简单的类,该类现在返回一种颜色以及该颜色的exportmetadata标签。但是,如果我将三个dll放入目录中,每个dll都有一个唯一的导出,则ImportMany最终会得到要加载的第一件事的三个副本,而其他都不存在。

public interface IColorMatch
{
    string ValidationMessage { get; }
}

public interface IColorMatchData
{
    string Color { get; }
}

及其实现,每个都在单独的dll中

[Export(typeof(IColorMatch))]
[ExportMetadata("Color","RED")]
class RedColor : IColorMatch
{
    public string ValidationMessage
    {
        get
        {
            return "RED";
        }
    }
}

[Export(typeof(IColorMatch))]
[ExportMetadata("Color","BLUE")]
class BlueColor : IColorMatch
{
    public string ValidationMessage
    {
        get
        {
            return "BLUE";
        }
    }
}

最后是加载所有代码的代码

[ImportMany]
IEnumerable<Lazy<IColorMatch, IColorMatchData>> Colors;

public void OnClick(object sender, RoutedEventArgs e)
{
    var catalog = new AggregateCatalog();
    catalog.Catalogs.Add(new DirectoryCatalog(AppContext.BaseDirectory));

    //Create the CompositionContainer with the parts in the catalog
    _container = new CompositionContainer(catalog,CompositionOptions.DisableSilentRejection);

    //Fill the imports of this object
    try
    {
        this._container.ComposeParts(this);
    }
    catch (CompositionException compositionException)
    {
        Console.WriteLine(compositionException.ToString());
    }

    //this is just for convenience while at a breakpoint  
    var debug = Colors.Select(x => x.Metadata.Color.ToLower());
    var list = Colors.Where(x => x.Metadata.Color.ToLower() == txtColor.Text.ToLower());
    if (list.Count() < 1)
    {
        list = Colors.Where(x => x.Metadata.Color == "Default");
    }
    foreach (Lazy<IColorMatch, IColorMatchData> item in list)
    {
        lstbox.Items.Add($"This was processed using code for the {item.Value.ValidationMessage}");
    }
}

,最终结果是,如果我仅使用目录中的red.dll启动UI,则调试列表将仅具有条目“ RED”和“ Default”。如果目录中只有blue.dll,则debug包含“ Blue”和“ Default”。如果目录中同时存在red.dll和blue.dll,则debug包含“ RED”,“ RED”和“ Default”。

很明显检测到两个副本,为什么为什么只将第一个加载两次? Default实例是在具有接口的基本文件中定义的,并且似乎可以共存。

0 个答案:

没有答案