Testing and Debugging MEF, Tips – Part 2


no comments

Testing and Debugging MEF, Tips – Part 2

this is the second post of a series that will offer some tips

about testing and debugging your MEF-able component and application.


in this post we will focus about debugging the most common, and most confusing,

MEF failure.


Assembly Loading Failure

the most common MEF runtime failure occurs because of missing assembly

which contain the MEF parts (Import, Export) or

the parts dependencies (like 3rd party components).


under the hood MEF is using reflection, which mean that MEF loading

behavior is similar to the reflection dynamic loading.


Tracing Loading Failure?

I will suggest 2 option for tracing the failure:


1. we can register to assembly resolve event (AppDomain.CurrentDomain.AssemblyResolve)

Code Snippet
  1. AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolveHandler;
  2. static Assembly OnAssemblyResolveHandler(object sender, ResolveEventArgs args)
  3. {
  4.     Logger.WriteLine("Assembly Resolve: " + args.Name);
  6.     return args.RequestingAssembly;
  7. }

the problem with that approach is that we may get some smoke events which

actually succeed (because of the .NET probing).


2. catching ReflectionTypeLoadException exception

Code Snippet
  1. try
  2. {
  3.     container.ComposeParts(p);
  4. }
  5. catch (ReflectionTypeLoadException ex)
  6. {
  7.     foreach (Exception exc in ex.LoaderExceptions)
  8.     {
  9.         Logger.WriteLine(exc.Message);
  10.     }
  11. }

we can wrap the composition using try catch scope.

and catch ReflectionTypeLoadException. this will

give us pretty good idea what’s got wrong.  



my suggestion is whenever possible, wrapping any composition and catch the ReflectionTypeLoadException, in other cases we can use the first technique.



Ohad Schneider should have credit for part of the code in this post.

kick it on DotNetKicks.com Shout it

Digg This
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>