Working with CompositionBatch in MEF

By | September 4, 2011

CompositionBatch is a new type introduced with MEF library that allows you to individually deal with Part instances. Generally when we are in a situation that we need to manually handle certain type, or more precisely when we need to create the types manually ourselves, it is recommended to use CompositionBatch. Basically you thing think CompositionBatch is just a replica of AggregateCatalog, but it isnt. CompositionBatch allows you to manually add/remove part instances to it and finally Compose using this CompositionBlock.

Remember, after the CompositionBatch is modified the container automatically triggers a Compose to update and compose parts. Hence all the Recomposable elements will be recreated again.

Let us look how to deal with it :

AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

CompositionBatch batch = new CompositionBatch();

Program p = new Program();
batch.AddPart(p);

CompositionContainer container = new CompositionContainer(catalog);
container.Compose(batch);

Here you can see I have used CompositionBatch to manually add a composable element to it. The object of Program is created manually and batch.AddPart will add the dependency of it. It might come handy when you do not need the object to be recreated to create dependency between the objects, when you actually have the object.

You can also use RemovePart to remove a part from the CompositionBatch manually. When you call the AddPart or RemovePart the parts are actually added to a collection called PartsToAdd and PartsToRemove, which will actually add or remove dependency when Compose is triggered.

CompositionBatch needs a call to Compose.

Read more about it from the links :

Managed Extensibility Framework – A Look

Steps to write a plugin based application with MEF

Thank you for reading.