2

I have a problem with a proof of concept application for MEF plugins. I have a simple class that for now returns a color and the exportmetadata tags that color. However if I place three dll's into the directory, each with a unique export, ImportMany ends up with three copies of the first thing to be loaded and, none of the others are present.

public interface IColorMatch
{
    string ValidationMessage { get; }
}

public interface IColorMatchData
{
    string Color { get; }
}

and the implementations, each in a separate 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";
        }
    }
}

and finally the code to load it all

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

and the final result is if I start the UI with only red.dll in the directory, the debug list will only have the entry "RED" and "Default". If I only have blue.dll in the directory, debug contains "Blue" and "Default". If have both red.dll and blue.dll in the directory at the same time, debug contains "RED", "RED", and "Default".

it obviously is detected two copies, why is instead just loading the first one twice? the Default instance is defined in the base files with the interfaces, and that one seem to coexist fine.

1
  • where is the problem i implemented your code and it is good runs well? Commented Jul 13, 2019 at 18:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.