4

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 ().

Palec
  • 12,743
  • 8
  • 69
  • 138
Jeevan Bhatt
  • 5,881
  • 18
  • 54
  • 82
  • Possible duplicate of [MEF vs. any IoC](https://stackoverflow.com/questions/1288376/mef-vs-any-ioc) – Palec May 19 '19 at 08:40

4 Answers4

12

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I find Ayende's blog post confusing. For example, MEF is *not* able to "query meta data without loading assemblies" and doesn't have "contract adapters" contrary to what the post says. There is a lot of hand-waving in that post. – Wim Coenen Dec 03 '10 at 16:30
1

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.

Ian Ringrose
  • 51,220
  • 55
  • 213
  • 317
1

Glen Block (former Product Manager of MEF) has covered this pretty well on his blog:

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
0

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.

Michael Shimmins
  • 19,961
  • 7
  • 57
  • 90