My company just began working on a large, modular WPF project. I’ve been doing some research and recently took some time to dig into the Managed Extensibility Framework (MEF). I’m quite impressed with the direction that the project is going. MEF is going to fulfill our modularity needs quite well.
At the same time, I have refactored Caliburn to use the CommonServiceLocator that P&P released last year. Caliburn is a loosely coupled set of UI services and requires dependency injection to work. I have IServiceLocator implementations of Windsor, StructureMap, Unity and Spring.NET. Many of these implementations are based on the adapter code that can be found on the CommonServiceLocator site. Interestingly, there isn’t an implementation of IServiceLocator for MEF.
As my current project needs MEF to solve modularity concerns and Caliburn to solve UI architecture issues, I spent some time today writing an IServiceLocator adapter for MEF. It turned out not to be too difficult, but the code is not pretty. This stems from the fact that MEF’s CompositionContainer is generics based, but ServiceLocatorImplBase uses Type instances. I had to resort to using reflection to interact with the underlying container. I’m going to post the code below so that you can see how to do this sort of thing, but also in hopes that someone like Glenn can correct any stupid stuff (I was hoping there is a non-reflection-based mechanism that I just didn’t see.)