Is is possible to continue after getting an error in ComposeParts?

Jun 2, 2010 at 7:52 PM

I've been using MEF to handle plugin loading in my application, and I have really liked it so far.  However, one issue I have is with CompositionContainer.ComposeParts.  If I load a plugin that fails to resolve its imports, then an exception is thrown.  That's fine and all, but what I'd really like to do is have MEF continue to load the rest of the assemblies from the specified directory.  Is this possible?  

Jun 5, 2010 at 7:21 AM


I'm having the same problem.

I have this:

public List<IProvider> ProviderPlugins { get; set; }


List<Type> types = new List<Type>();

to which i explicitly add my types. Then I do:

 var catalog = new TypeCatalog(types);
 var container = new CompositionContainer(catalog);

If any of the types throws an error in its constructor, the whole import fails:

Resulting in: An exception occurred while trying to create an instance of type 'blagh'.

Resulting in: Cannot activate part 'blagh'. Element: blagh -->  blagh -->  TypeCatalog (Types='A, B, ...').

Resulting in: Cannot get export 'blagh (ContractName="IProvider")' from part 'blagh'. Element: blagh(ContractName="IProvider") -->  blagh -->  TypeCatalog (Types='A, B, ...').

Resulting in: Cannot set import 'ProviderPlugins (ContractName="IProvider")' on part 'Providers'.Element: Providers.ProviderPlugins (ContractName="IProvider") -->  Providers

   at System.ComponentModel.Composition.CompositionResult.ThrowOnErrors(AtomicComposition atomicComposition)
   at System.ComponentModel.Composition.CompositionResult.ThrowOnErrors()
   at System.ComponentModel.Composition.Hosting.ComposablePartExportProvider.Compose(CompositionBatch batch)
   at System.ComponentModel.Composition.Hosting.CompositionContainer.Compose(CompositionBatch batch)
   at System.ComponentModel.Composition.AttributedModelServices.ComposeParts(CompositionContainer container, Object[] attributedParts)

I can work around this by checking first that each export can be constructed without error:

            try {
                blagh b 
                    = new blagh();
                types.Add( b.GetType() );
            } catch (Exception ce) { }

but it would be nice if there was something I could instead add to the [ImportMany], or failing that, an [Export]?






Jun 5, 2010 at 7:48 PM

You can import things as Lazy and then you control when the object is construct/composed and can handle the error accordingly. See for a code snippet.

Jun 19, 2010 at 6:04 AM
Thanks, Wes! That's really helpful. I'm reading up on Lazy now because that is an entirely new concept to me.