MEF2: Imports not found unless explicitly exported

433 Views Asked by At

I'm trying to get MEF2 attribute-less/convention-based registration working in my app. What I'm seeing is that if I omit the [Export] attribute, neither the ComposeParts call or GetExports call result in any items.

If I add an [Export(typeof(IGuiModule))] attribute to my class, it then gets picked up fine but with the (reasonable) warning:

"An Export specification convention that would apply to type 'Core.Models.DeviceListView' has been overridden by attributes applied in the source file or by a prior convention."

Have I missed something here, or have the wrong expectations? I am led to believe the MEF2 approach allows you to import without needing an explicit export attribute?

The info I've found is a bit mixed and fragmented, with various sources showing different info (as MEF has evolved, I suppose).

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class ModuleMetadata : Attribute, IModuleMetadata
{
    public ModuleMetadata(string aName)
    {
        Name = aName;
    }
    public string Name { get; private set; }
}

public class Core
{
    [ImportMany(typeof(IGuiModule))]
    public List<ExportFactory<IGuiModule, IModuleMetadata>> GuiModuleImports;

    public Core()
    {
        var rb = new RegistrationBuilder();
        rb.ForTypesDerivedFrom<IGuiModule>().Export<IGuiModule>();
        var catalog = new DirectoryCatalog(@"d:\prog\core\", "*.dll", rb);
        var container = new CompositionContainer(catalog);
        var gx = container.GetExports<IGuiModule, IModuleMetadata>();
        container.ComposeParts(this);
    }
}

Exported class:

// We appear to *need* this attribute: [Export(typeof(IGuiModule))]
[ModuleMetadata("Device List")]
public partial class DeviceListView : UserControl, IGuiModule
{
    public DeviceListView() {...}
}
0

There are 0 best solutions below