Question about mixing MEF and Unity

Posted by Dave on Stack Overflow See other posts from Stack Overflow or by Dave
Published on 2010-05-20T18:37:52Z Indexed on 2010/05/20 20:00 UTC
Read the original article Hit count: 401

I'm finally diving into Unity head first, and have run into my first real problem. I've been gradually changing some things in my app from being MEF-resolved to Unity-resolved. Everything went fine on the application side, but then I realized that my plugins were not being loaded.

I started to look into this issue, and I believe it's a case where MEF and Unity don't mix. Plugins are loaded by MEF, but each plugin needs to get access to the shared libraries in my application, like app preferences, logging, etc.

Initially, my plugin constructor had the ImportingConstructor attribute. I then replaced it with InjectionConstructor so that Unity could resolve its shared library dependencies. But because I did that, MEF no longer loaded it! Then I used both attributes, which compiled, but then I got a composition error (MEF). I figured that this was because the constructor takes a parameter that was once resolved by a MEF Import, so I removed all parameters. As expected, now MEF was able to load my plugin, but because the constructor needs to call into the interface that was once passed in, construction fails.

So now I'm at a point where I can get MEF to start to load my plugin, but can't do anything with it because the plugin relies on shared libraries that are registered with Unity. For those of you that have successfully mixed MEF and Unity, how do you go about resolving the references to the shared libraries with Unity? It seems like a catch-22, where in order to have Unity work with the plugin, I'd have to create the plugin via Resolve, but then it's impossible to use MEF.

UPDATE

I can work around this problem by using an ImportingConstructor for the plugin that takes an IUnityContainer, and then call Resolve for each interface that I need, but although it works, it is incredibly lame to do it this way, as this would require all plugin authors to remember to save a reference to the passed in IUnityContainer...

© Stack Overflow or respective owner

Related posts about MEF

Related posts about unity