Roman.Pavelko
Roman.Pavelko

Reputation: 1655

MEF 2 attribute-less importing

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?

Upvotes: 1

Views: 1459

Answers (1)

Panos Rontogiannis
Panos Rontogiannis

Reputation: 4172

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:

ImporterClass t = new ImporterClass();        
container.ComposeParts(t);

with:

ImporterClass t = container.GetExportedValueOrDefault<ImporterClass>();

And change the ImporterClass.Exporter to public. MEF Conventions allow imports only on public properties.

Upvotes: 2

Related Questions