'.NET 6 MEF 2 Export plugins via Lazy with metadata

In .NET Framework using MEF1 I would get my plugins as a Lazy<IPlugin, IPluginMetadata>. Having a collection of plugins, being able to filter on the metadata to load the plugin that I want, whenenver I want it:

[ImportMany(typeof(IPlugin))]
private IEnumerable<Lazy<IPlugin, IPluginMetadata>> _MyPlugins;


  public interface IPluginMetadata
  {
    string MyType { get; }
    string Foo { get; }
    bool CanBar { get; }
    bool IsUsable { get; }
  }

[Export(typeof(IDestConnectorPlugin))]
[ExportMetadata("MyType", "something")]
[ExportMetadata("Foo", "yes")]
[ExportMetadata("CanBar", true)]
[ExportMetadata("IsUsable", true)]

Now in .NET 6 I seem to struggle to get Lazy and the IPluginMetadata working.

I can easily get my plugins using IPlugin:

var conventions = new ConventionBuilder();
conventions.ForTypesDerivedFrom<IPlugin>()
.Export<IPlugin>()
.Shared();

var configuration = new ContainerConfiguration();
// configuration.WithAssemblies(..., conventions); // code removed here for brevity 

using (var container = configuration.CreateContainer()) {
  var plugins = container.GetExports<IPlugin>();
}

When I try to change the export to:

.Export<Lazy<IPlugin, IPluginMetadata>>()

Doesn't seem to work.

When I try to add metadata:

// ..
.Export<IPlugin>((exbuilder) => MyExportBuilder(exbuilder))
// ..

private static void MyExportBuilder(ExportconventionBuilder builder) 
{
  builder.AddMetadata("Foo", x => x.GetCustomAttributes<ExportMetadataAttribute>().Where(x => string.Equals(x.Name, "Foo").FirstOrDefault().Value);
}

I can't seem to get it working as Lazy<IPlugin, IPluginMetadata> or having the IPluginMetadata.

Any suggestions?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source