I spent several hours trying to figure out how to pass parameters to a plugin constructor via MEF (System.Composition) but all to no avail. Needless to say, there are very few relevant docs and a look through the source code didn't help.
This used to be really easy to do, using the CompositionHost.ComposeExportedValue method, but in the .NET Core version I can't seem to find anything that works. I've enclosed my incomplete code, below, followed by the exception that is thrown.
Any help in this regard would be greatly appreciated. Thanks....
using System;
using System.Composition;
using System.Composition.Hosting;
using System.Reflection;
namespace MefMe
{
public interface IPlugin
{
void Alert();
}
[Export(typeof(IPlugin))]
public class Plugin : IPlugin
{
private string code;
[ImportingConstructor]
public Plugin(string code)
{
this.code = code;
}
public void Alert() => Console.WriteLine(code);
}
class Program
{
static void Main(string[] args)
{
var config = new ContainerConfiguration()
.WithAssembly(Assembly.GetEntryAssembly());
var container = config.CreateContainer();
// Throws a CompositionFailedException; see notes
var plugin = container.GetExport<IPlugin>();
plugin.Alert();
}
}
}
System.Composition.Hosting.CompositionFailedException occurred
HResult=0x80131500 Message=No export was found for the contract 'String' -> required by import 'code' of part 'Plugin' -> required by initial request for contract 'IPlugin' Source= StackTrace: at System.Composition.Hosting.Core.ExportDescriptorRegistryUpdate.CheckTarget(CompositionDependency dependency, HashSet1 checked, Stack
1 checking) at System.Composition.Hosting.Core.ExportDescriptorRegistryUpdate.CheckDependency(CompositionDependency dependency, HashSet1 checked, Stack
1 checking) at System.Composition.Hosting.Core.ExportDescriptorRegistryUpdate.CheckTarget(CompositionDependency dependency, HashSet1 checked, Stack
1 checking) at System.Composition.Hosting.Core.ExportDescriptorRegistryUpdate.Execute(CompositionContract contract) at System.Composition.Hosting.Core.ExportDescriptorRegistry.TryGetSingleForExport(CompositionContract exportKey, ExportDescriptor& defaultForExport) at System.Composition.Hosting.Core.LifetimeContext.TryGetExport(CompositionContract contract, Object& export) at System.Composition.CompositionContext.GetExport(CompositionContract contract) at System.Composition.CompositionContext.GetExport[TExport](String contractName) at MefMe.Program.Main(String[] args) in C:\Users\louis\Desktop\MefMe\MefMe\Program.cs:line 36