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 a sample code which demonstrates the error –
In this example, “Task.WaitAll” would throw an exception because of the concurrent hit on GetExportedValue.
How to fix this –
Well, the fix is as easy as it can be. You need to construct the container as thread safe –
In the second parameter we pass ‘true’ to make it thread-safe.
That’s it! dead easy.
You should note that it has a performance hit though, obviously.