MEF & Exceptions

Mar 22, 2010 at 3:12 PM

Hi everybody,
I would like to create a "small system" where when the CompositionContainer composes parts, and one of them threw an exception inside the constructor, the container catch it, notifies to the "client" and removes the part which thrown the exception.

With a bit of debugging I've found that is the SetImport method of ComposablePart that creates the plugin's instance, or better the SetImport method of ReflectionComposablePart.

Can I change this behavior in a simple way or I need to rewrite the TypeCatalog (It's the only one that uses the ReflectionComposablePart) and the ReflectionComposablePart?

Thanks
Federico

Developer
Mar 22, 2010 at 11:13 PM

No there is not any simple way to do this. Even if you wrote your own TypeCatalog and supporting types it wouldn't really be possible to do because of the lazy nature of the composition.

For example someone could import Lazy<IFoo> and the backing instance of IFoo will not be constructed until someone calls .Value on the lazy object instance. At which point the composition has already handed out an instance of that part from the catalog and you can't simply undo that and remove it from the catalog.

In general we treat exceptions occurring during construction as fatal and will cause the entire composition to fail.