Search code examples
c#mefcomposition

Why does enumerating MEF parts cause container initialization to fail?


The following code throws an InvalidOperationException, message: Global Container Already Initialized

        var aggcat = new AggregateCatalog();
        aggcat.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly().Location));

        // This line does something to the catalog
        aggcat.Parts.ToArray();

        _container = new CompositionContainer(aggcat, true);

        // Exception gets thrown here
        System.ComponentModel.Composition.Hosting.CompositionHost.Initialize(_container);

It works fine when I comment out the Parts.ToArray() line. What is happening here?


Solution

  • I never figured out the specifics of it, but the Assembly Catalog does a lot of lazy loading. Calling ToArray() forces it to complete the deferred processing.