MEF property injection doesn't occur

1.4k views Asked by At

I have a problem when retrieving information from an imported attribute. The attribute remains null after calling .ComposeParts(), but the composition is OK, because I can call .GetExportedValues() afterwards and I get the needed instance. Here is the code:

Bootstrapper doing the composition

 [Export]
public class Bootstrapper
{
    public void Run()
    {
        doComposition();
    }

    private void doComposition()
    {
        var catalog = new AggregateCatalog();

        catalog.Catalogs.Add(new DirectoryCatalog("./Applications"));
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(Loader).Assembly));

        Container = new CompositionContainer(catalog);
        // Apps = Container.GetExportedValues<IApplication>(); - this gets me the IApplication(s), but I dont understand why Apps isn't injected automatically
        Container.ComposeParts(catalog);
        IEnumerable<IApplication> app = Container.GetExportedValues<IApplication>();
    }

    public CompositionContainer Container { get; set; }

    private IEnumerable<IApplication> apps;

    [ImportMany(typeof(IApplication))]
    public IEnumerable<IApplication> Apps
    {
        get { return apps; }
        set
        {
            apps = value;
        }
    }

Signature of one of the classes implementing IApplication

[Export(typeof(IApplication))]
public class MDFApplication : IApplication {...}

Any pointers are appreciated, thanks a lot.

1

There are 1 answers

0
Panagiotis Kanavos On BEST ANSWER

You never call any code to compose your Bootstrapper class. ComposeParts will create the catalog, it will not create or compose any classes until you specifically ask for them.

The container doesn't search for all members that require an import when you call GetExportedValues. It either returns an already existing instance or it creates a new one, satisfying all its import attributes.

In other words, the following code will return a fully constructed Bootstraper class:

        var b= Container.GetExportedValue<Bootstrapper>();
        Debug.Assert(b.Apps!=null);            

In order to compose an object that already exists, you need to call the SatisfyImportsOnce method. This will find all imports and satisfy them if possible. E.g.

        Container.SatisfyImportsOnce(this);
        Debug.Assert(this.Apps != null);