Working with CompositionBatch in MEF

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434