Search code examples
mefanti-patternsservice-locator

Is MEF a Service locator?


I'm trying to design the architecture for a new LOB MVVM project utilising Caliburn Micro and nHibernate and am now at the point of looking into DI and IOC.

A lot of the examples for bootstrapping Caliburn Micro use MEF as the DI\IOC mechanism.

What I'm struggling with is that MEF seems to by reasonably popular but the idea of the Mef [Imports] annotations smells to me like another flavour of a Service Locator?

Am I missing something about MEF whereby almost all the examples I've seen are not using it correctly or have I completely not understood something about how it's used whereby it side steps the whole service locator issues?


Solution

  • I suppose if you were to just new up parts that had property imports and try to use them, then you could run into some of the same problems described here: Service Locator is an Anti-Pattern

    But in practice you get your parts from the container, and if you use [Import] without the additional allowDefault property, then the part is required and the container will blow up on you if you ask for the part doing the import. It will blow up at runtime, yes, but unlike a run of the mill service-locator, its fairly straightforward to do static analysis of your MEF container using a test framework. I've written about it a couple times here and here.

    It hasn't been a problem for me in practice, for a couple of reasons:

    1. I get my parts from the container.
    2. I use composition tests.
    3. I'm writing applications, not framework code.