MEF – Thread Safety and GetExportedValue

January 2, 2011

In one of our projects, we encountered odd exceptions that were thrown out of “GetExportedValue<T>” from the CompositionContainer of MEF. There are 2 exceptions that I have seen that are related to the same issue: System.InvalidOperationException: GetExportedValue cannot be called before prerequisite import 'MyType..ctor(Parameter="myParameter", ContractName="MyOtherType")' has been set System.ArgumentException: An item with the same key has already been added. After digging into the matter, we found that these errors occurred while trying to call GetExportedValue concurrently from numerous threads. Yeah, simple as that, MEF isn’t thread-safe in its default form. Following is...
tags: ,