I’m working on an application using MEF 2. I wanted to try attribute-less way of designing plugins and now I’m trying to figure out why one of my objects does not seem to be satisfying its Import.
Below is sample code.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Registration;
using System.Reflection;
namespace MEF2
{
class Program
{
static void Main(string[] args)
{
var builder = new RegistrationBuilder();
builder.ForType<ExporterClass>().Export<ExporterClass>();
builder.ForType<ImporterClass>().Export().ImportProperties(p => p.Name == "Exporter");
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), builder);
CompositionContainer container = new CompositionContainer(catalog);
ImporterClass t = new ImporterClass();
container.ComposeParts(t);
t.ShowWalkers();
}
}
public class ExporterClass
{
public void Write()
{
Console.WriteLine("Test");
}
}
public class ImporterClass : IPartImportsSatisfiedNotification
{
//[Import]
private ExporterClass Exporter { get; set; }
public void ShowWalkers()
{
if (Exporter != null)
Exporter.Write();
}
public void OnImportsSatisfied()
{
Console.WriteLine("IPartImportsSatisfiedNotification");
}
}
}
OnInputSatisfied event is fired but Exporter property is still null. If I uncomment [Import] attribute everything works.
What should I do to import without an attribute?
I’m not sure if you can use CompositionContainer.ComposeParts with MEF Conventions. I think it is for the attributed model only.
To make your example work replace:
with:
And change the
ImporterClass.Exportertopublic.MEF Conventionsallow imports only on public properties.