I’ve been comparing Unity and MEF (to be used in Prism) and was going towards MEF. Alas, recently I saw Unity’s cool runtime dependency resolving – If I want to add a module, I should just add its view type using ServiceLocator and, if I have a dependency constructor stating the view model, Unity will initialize it for me, along with the VM’s dependencies (in other services and modules).
Is this kind of behavior supported in MEF?
Thanks.
Let’s ignore Unity and MEF for now, and look at what your describing.
This mechanism is called Dependency Injection (DI) and is an implementation of the Inversion of Control (IoC) principle. Also note, that DI is not the same as Service Location (SL).
Your particular example is called constructor injection, whereby dependencies are injected into the type being constructed, therefore:
Is a site for constructor injection. Now let’s look at the two different container technologies:
Unity is an IoC container in the traditional sense. You register known parts at runtime, which builds a catalog, and when you request a part from the container, it will automatically resolve the required dependencies.
MEF is built around discovery and composition of unknown parts, i.e., it builds it’s container by building a list from export providers (either catalogs, or other providers). When you request a part to be composed, it by default will select a parameter-less constructor, e.g.:
Unless you decorate the target constructor with an
[ImportingConstructor]attribute, which allows MEF to select the appropriate constructor, and resolve any dependencies:Also note, that MEF supports property injection through
[Import]and[ImportMany]attributes:Although, my preference is to use constructor injection, as it better describes the dependencies your class requires to operate.
Now, at the time of writing, this is appropriate for MEF 1.0 using the Attributed Programming Model. With MEF 2.0, (and also via MEFContrib), there are mechanisms to support registration-based and convention-based programming models.
So in short, yes you can use MEF for Dependency Injection.