What Is The Difference Between an IoC Container and MEF?

Today a conversation sparked off on Twitter, started by Jimmy Bogard and Matt Hinze, and then carried on by myself and Glenn Block. The basic starting point was what the difference was between using an IoC container like Windsor or StructureMap and using MEF (the Managed Extensibility Framework)

I started off by answering a question from Jimmy, he wanted the one paragraph sales pitch for MEF that didn’t include technical terminology … I guess he was asking why MEF is a better option than one of the IoC containers we all love and hopefully all use religiously.

My key answers were:

MEF allows you to write your application as a series of much simpler mini applications, and have those brought together to create a much great whole

IoC container = service level components, MEF = Autonomous Components. A MEF "part" will probably use an IoC container

This sparked some comments from Glenn where he wanted to clarify that sometimes an IoC container is the right choice, sometimes MEF is, and sometimes both are. Luckily we are both pragmatic, so not much to disagree with there. He pointed to two of his blogs on the subject, I recommend reading them highly, they will do a much better job than I could at explaining the detail of the decision points, Should I use MEF for my general IoC needs? and Should I use MEF with an IoC container?

What’s Wrong With IoC Containers?

What an IoC container is very good at is low level control of your code, your dependency graphs, your lifestyle management, and gives you great low level ways to deal with facilities, factories, decorators and AOP. In just about any code base that goes past spike stage, I use an IoC container of some sort, it is just a fools errand to try and write and application without one these days. The keyword “new” is in my code smells book.

However, what an IoC container is pretty poor at is enforcing boundaries. Sure you could use an IoC container to write much larger applications, but as Glenn rightly pointed out, the central configuration becomes a headache. In fact, the central registration can rapidly become the equivalent of using global variables, you never really know what is using what as everything has access to everything else.

Most of the containers give you the capability to have child containers to try and deal with this situation, and while they do limit the global access issue, they are pretty hard to manage in their own right, and you can without some proper thought end up with a spaghetti mess of containers replacing your spaghetti mess of components.

An Architectural Solution To The Problem

To me, MEF is an architectural solution, while an IoC container is a code level solution. They both have their places in an application, but what MEF is exceptionally good at is creating process boundaries.

One of the core underlying principles of good use of an IoC container is that you only ever reference a container at a process boundary – in most applications that means it is probably referenced in your bootstrapping code inside your web application (maybe Global.ascx), or inside an HttpModule around your web services, but from that point on, your code should never reference the container again – the magic of an IoC container comes from relinquishing all object construction and dependency graph resolution to it.

But this means in a larger application, you may end up with massive containers with hundreds of registered components, and in reality most operations will only use a small handful at a time.

In most larger systems you would naturally have parts of the system you want to devolve into discrete components, or Autonomous Components. Doing this with an IoC container starts to lead you down an architectural design geared around the limitations of the IoC container, and not necessarily driven by good architectural principles.

What MEF allows you to do is to break the system apart easily, or as Glenn referred to it, MEF allows you to easily create composite applications. These composite parts can operate as Autonomous Components, in almost total isolation from the core application, and therefore they provide a natural boundary without having to use things like web of WCF service layers just for that purpose. Oddly the MEF terminology that Jimmy wanted to avoid in his original question was “part” and yet it fits naturally in this context.

Russian Dolls

As I started off by saying, I would almost always end up using an IoC container in any application I was to write, even a fairly small scale one. If we look at these MEF parts as now being Autonomous Components, and therefore operating as mini applications, it now becomes apparent that they will themselves need a way to create service components and dependency graphs, and while MEF could in theory do a lot of that, it’s just not the best fit for the job.

So it’s pretty certain that inside your MEF part you will be using yet another IoC container for object resolution, but now you don’t have a massive central registry, but one specifically geared to the MEF part in question.

And this pattern can recurse if needed, each time providing a clean boundary within your application.

A Real World Example

The last “large scale” system I worked on where I had the opportunity to put some of these ideas into practice was an insurance portal. This portal was responsible for providing insurance quotations, but across a massively diverse and inconsistent set of products.

The solution we came to in the end was a combination of all of the above principles – we had a web application that held a Castle Windsor container in Global.ascx, that container was responsible for instantiating everything from controllers backwards, and all of the service components they used.

But some of those controllers needed to call our product plugins, and in this case we actually used Castle Windsor to use MEF to instantiate the plugins (MEF parts). Within each product plugin we had another set of bootstrapping code that had it’s own instance of a Castle Windsor container, and it’s own registry specific to that plugin.

The plugins were actually used by a number of points in the application, some in process, and some out of process, either on other servers or just behind service or service bus boundaries – what MEF allowed us to do was create an independently deployable package that was self contained and self sufficient, without the need for managing masses of registration information – trying to use an IoC container for this would have been a mini-nightmare, but with MEF it was almost a pleasure.


Posted 12-18-2009 6:50 AM by Jak Charlton

[Advertisement]

Comments

Bjoern Rochel wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-18-2009 3:21 AM

Interesting post, though I'm still not quite convinced of MEF. At least not regarding the modularization argument.

The global configuration is a problem in large scale systems but for instance StructureMap can deal with highly modularized registration without using a container hierarchy or multiple containers.

In practice this means that you create a Registry-class per plugin-assembly (residing in the plugin-assembly) and uitilize StructureMaps scanning capabilities.

This totally works for me and gives me the kind of registration modularization I THINK you described in this post.

Personally I think the big difference between classic IoC and MEF is static and dynamic composition. MEF seems to be good for extensibility scenarios where it is a requirement to load and unload plugins at runtime, IIRC. (in constrast to the IoC who does the loading only at startup time)

-Björn

Andreas Håkansson wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-18-2009 7:10 AM

Bjoern,

MEF load into the current app domain so unloading at runtime is not possible, you would have to recycle the entire app domain..  loading into a different app domain can be done with customization but then you are faced with marshaling and the need to inherit MarshalByRefObject

Yuriy wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-18-2009 7:39 AM

I prefer to live with only attributes and without configuration files where it is possible, so I tried to use MEF for both internal dependency injection inside smaller modules and for composition from large parts.  It almost worked for me after I have created special filters for internal and external part catalogs.  Unfortunately, having single [export] attribute is not very convenient if you have to publish parts either to internal or external world.  

It is solvable with custom attributed model or just proper filtering of catalogs, but definitely MEF could be more helpful here.

Mark wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-18-2009 5:19 PM

At first glance, MEF is sort of like OSGi. So if you want to see how they (IoC and MEF) work today (not wait for Microsoft to finally get on the modularity bus), look at how Spring and OSGi work together.  

While there seems to be cross-over, they really serve different purposes.

Glenn Block wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-18-2009 8:43 PM

Nice post Casey. It's a good use case for us of one way of putting MEF together with an IoC. Division of responsibilities seems to be one of the big challenges, yet in your model you have found a clear part that works.

@Bjoern

MEF catalogs are statically analyzable, Registries are imperative code, which MEF's model is declarative. The difference is imperative code is not statically analyzable, while MEF's is. That means outside of the runtime environment we can determine what will happen, and within the runtime environment we can guarantee composition is stable, and prevent other parts from destabilizing it.

@Yuriy another option to look into is container

hierachies for separation.

@Mark, I would argue we're on the modularity bus. That's why we're doing MEF ;-)

Bjoern Rochel wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-19-2009 2:57 PM

@Glen

Wasn't aware of that. Interesting feature for 3rd party plugin integration. Going to take a look into that...

Mark wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-19-2009 4:30 PM

@Glenn, my "on the bus" comment was based on the MEF website saying "Disclaimer: MEF is in development."   I meant "being on the bus" by having  GA release. But I can agree that developing it is on a bus too. :)

On the other hand it is saddening/maddening/frustrating that Microsoft is yet again reinventing  the wheel. Especially so for us who work in heterogeneous environments.

Bart Czernicki wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-20-2009 4:39 PM

Nice article!  Speaking of a real world example...it would be nice if there was a full-blown example of MEF and Silverlight available to see "best practices"

Glenn Block wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-20-2009 5:11 PM

Mark, it's also currently in .NET 4.0 Beta 2 and Silverlight 4 beta 1.  So you could say multiple busses. ;-)

Glenn

Franz See wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-21-2009 2:55 AM

IoC is a deprecated term for Dependency Injection. The meaning of Inversion of Control practically applies to any types of framework wherein the control is 'inversed' - it is not limited to dependency injections.

Jak Charlton wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-21-2009 5:15 AM

@Franz

"IoC Container" is the general term for components like Windsor, Unity, Ninject, Autofac, and StructureMap etc

John Sonmez wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-21-2009 10:48 AM

I am not 100% convinced on containers for IoC patterns.  IoC definitely exists without dependency injection.  You highlight an important issue, that dependency injection becomes unwieldy in large applications with large containers.  I use containers myself, but sometimes I wonder if I am making the code complex by hiding the understanding of how things get instantiated.

You have some excellent points here though.  Especially with MEF.  

Mark Nijhof wrote re: What Is The Difference Between an IoC Container and MEF?
on 12-23-2009 7:25 PM

Hi Jak,

Great post. I was wondering how you deal with the static nature of IoC's I mean even when you separate the different components and have them all use an IoC will these not all use the same instance in the end?

-Mark

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)