The main difference is that with a unit you will explicitly register every class that you want to use in the composition:
var container = new UnityContainer(); container.RegisterType<IFoo,Foo>(); container.RegisterType<IBar,Bar>(); ... var program = container.Resolve<Program>(); program.Run();
In MEF, on the other hand, you mark classes with attributes, rather than registering them somewhere else:
[Export(typeof(IFoo))] public Foo { ... }
At first glance, this looks like a slight syntactic difference, but in fact it is more important. MEF is designed for dynamic part detection. For example, using DirectoryCatalog you can design your application so that it can be expanded by simply dropping new DLLs in the application folder.
In this example, MEF will find and instantiate all classes with the [Export(typeof(IPlugin))] attribute in this directory and pass these instances to the Program constructor:
[Export] public class Program { private readonly IEnumerable<IPlugin> plugins; [ImportingConstructor] public Program( [ImportMany(typeof(IPlugin))] IEnumerable<IPlugin> plugins) { this.plugins = plugins; } public void Run() {
Point of entry:
public static void Main() { using (var catalog = new DirectoryCatalog(".","*")) using (var container = new CompositionContainer(catalog)) { var program = container.GetExportedValue<Program>(); program.Run(); } }
To accommodate such dynamic linking scenarios, MEF has the concept of “stable composition”, which means that when it falls into a missing dependency somewhere, it will simply mark this part as inaccessible and will continue composition anyway.
A stable composition can be very useful , but it also makes it very difficult to debug a failed composition . Therefore, if you do not need dynamic part detection and “stable composition”, I would use a regular DI container instead of MEF. Unlike MEF, regular DI containers give clear error messages when there is no dependency.
It is also possible to get the best of both worlds using a DI container that integrates with MEF, such as Autofac . Use Autofac to build the main application and MEF for parts that need to be dynamically extensible.