MEF – Thread Safety and GetExportedValue

Sunday, 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: ,
37 comments

MEF – Conventional catalog for registering non-attributed parts

Monday, October 18, 2010

As part of the task where I had to upgrade an existing WPF project to PRISM 4.0 and work with MEF, one of the requirements was to support registering existing non-attributed parts. Consider the following example - Code Snippet public interface IFoo { }   public class Foo : IFoo { }   static void Main(string args) {     //This is the desired thing to do     myCatalog.Register<IFoo, Foo>(); } As you can see, type Foo has no export definitions set on it. One...
tags: ,
no comments

MEF – Runtime Type Catalog, support multi registrations in runtime

Sunday, October 17, 2010

Recently, I dug deep into MEF because I was involved in a project where there was a decision to upgrade the WPF client to PRISM 4 and advance to using MEF alone instead of Unity. While many argue that MEF isn’t yet a full DI framework, it still provides an easy way to enable application extensibility in your projects. One of the tasks that I had while upgrading the client to PRISM 4, is to keep supporting type registration in runtime, something in the sort of the following - Code Snippet ...
tags: ,
no comments