I am studying MEF 2. Below code throws below exception:
An unhandled exception of type 'System.Composition.Hosting.CompositionFailedException' occurred in System.Composition.TypedParts.dll
Additional information: Missing dependency 'MessageSenders' on 'MEFStudy.Program'.
when calling the SatisfyImports() method. Why?
using System;
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.Reflection;
namespace MEFStudy
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
[ImportMany]
private List<IMessageSender> MessageSenders { get; set; }
public void Run()
{
Compose();
foreach (IMessageSender sender in MessageSenders)
{
sender.Send();
}
}
private void Compose()
{
CompositionHost host = new ContainerConfiguration().WithAssembly(Assembly.GetExecutingAssembly()).CreateContainer();
host.SatisfyImports(this); // <=========== HERE
host.Dispose();
}
}
public interface IMessageSender
{
void Send();
}
[Export(typeof(IMessageSender))]
public class EmailSender1 : IMessageSender
{
public void Send()
{
Console.WriteLine("EmailSender1");
}
}
[Export(typeof(IMessageSender))]
public class EmailSender2 : IMessageSender
{
public void Send()
{
Console.WriteLine("EmailSender2");
}
}
}
Update 1
According to here, there are 2 versions of MEF.
- non-portable one shiped with .NET Framework
- portable one available on NuGet
The List<IMessageSender>
approach works with non-portable one. But not with the portable one. Is this a bug?