Thursday, April 11, 2013

Unity vs. MEF - right for you, one is...

Visual Studio Magazine - Unity vs. MEF: Picking the Right Dependency Injection Manager

Peter Vogel compares both of the Microsoft dependency injection managers/inversion of control containers and comes up with a decision tree for picking the correct one.

I think dependency injection containers make it so much easier to implement designs that include many dedicated objects that I'm not sure I could live without one anymore. Microsoft, though, provides two: the Managed Extensibility Framework (MEF), which is part of the Microsoft .NET Framework, and the Unity Container (Unity), which is available as a NuGet download. While there are also several open source tools available, these are the two that are easiest to add to your project. So the question is: Which should you use?

I've discussed MEF and Unity separately, but it's worthwhile to take the time to discuss what I like about each of them and when to use each. One caveat: Both tools are sufficiently "feature rich" that I'm almost certain to get something wrong. I hope comments on this article will address any glaring errors on my part.

First, an overview: Both tools allow you to define containers that you can load with classes or objects. Once you load a container with classes, both frameworks will instantiate the classes and hand you back the resulting objects. Both frameworks allow you to specify what values are to be passed to constructors or used to set properties and call methods when classes are instantiated. Both containers allow you to control the lifetime of those objects -- allowing you, for instance, to specify that only a single instance of some object is ever to be created (effectively implementing the singleton pattern).


Unity vs. MEF: The Decision Tree


The good news is both MEF and Unity are excellent tools, so neither is a bad choice. The bad news is, three months after picking one, you'll run into a problem that would've been easier to solve with the other tool.


Peter's closing sentence made me laugh out loud. So, so true.

Currently I'm on the Unity track as I'm building a Prism app, and it seemed the Unity extensions just felt more natural.

No comments: