Search code examples
mef

What's the difference between CompositionBatch and catalogs?


I'm trying to wrap my brain around MEF, and one thing I'm struggling with is CompositionBatch.

CompositionBatch appears to be a way to add or remove exports to the MEF system, but apparently it can't remove something that was added via a catalog, so it's limited in usefulness. It also, for some reason, operates at the container level, instead of at the catalog level with everything else that registers types in MEF.

As far as I can tell, CompositionBatch is just a redundant way of doing what you could already do with catalogs. If I want to register two new types after my application has started, I don't need CompositionBatch; I could just as well pass an AggregateCatalog to my container, and then later when I'm ready, create a TypeCatalog from the two new types I want to register, add it to the AggregateCatalog, and everything would just work. And yet there's CompositionBatch, which solves this catalog problem by adding methods to the container instead.

What am I missing? Why does CompositionBatch exist? Does it, in fact, do anything that you can't do with what was already there? Why do we need a way to do the same thing at the container level?


Solution

  • If a type is in a catalog, MEF will create an object of that type when needed. A CompositionBatch lets you add objects to the composition that you've created yourself. We recommend sticking to catalogs in general, but there are situations where you need to create an object yourself, or it is created by some other component (for example the XAML parser) and you need to put it in the container.