In which scenario should we use which? How to decide on which one to choose? And under which circumstances would we choose to use both together?
I have previously worked with Unity Container (unity-container).
In which scenario should we use which? How to decide on which one to choose? And under which circumstances would we choose to use both together?
I have previously worked with Unity Container (unity-container).
Tricky question - since the two do indeed overlap to a certain degree.
I would say this:
use any useful IoC if you're primarily concerned about dependency injection for the sake of decoupling your components, e.g. for the ability to be able to inject a mock instead (for testing)
use MEF especially if you're more into being extensible, e.g. be able to "load all assemblies from that directory that export a certain interface", and if you need to be extensible and open for third parties (like Visual Studio: offer a public API so others can write an extension for your app). This is where MEF really shines
For MEF and Unity, there's also the MEF and Unity Integration Layer to combine the strengths of both tools together.
I would also recommend you check out Ayende's excellent blog post on what differentiates MEF from an IoC.
MEF shines when you have 3rd parties writing plug-ins, that implement interfaces and you wish to be able to version your interface without breaking the 3rd party plug in you can’t recompile. In exchange MEF is more complex than a raw IoC.
So I would say IoC if everything is compiled as part of the same build system, and MEF if you need to cope with add-ins you can’t recompile yourself.
Glen Block (former Product Manager of MEF) has covered this pretty well on his blog:
I heard a great explanation of this (apologies to the author, I've forgotten who it was): At a very high level, IoC is good when you want one thing for a given interface, MEF is good for when you want all things from a given interface.
For instance in IoC you want to return a specific single concrete class for an interface:
For<ICarFactory>().Use<CarFactory>();
Whenever you want to use a ICanFactory
you will get a CarFactory
.
MEF is good for saying give me all the car factories:
CheapCarFactory : ICarFactory
FamilyCarFactory : ICarFactory
LuxuryCarFactory : ICarFactory
Etc.