Sunday, July 8, 2012

Custom Injection of MEF Container

I have a requirement in one of the projects at work where we need to populate MEF container with objects that are created at run time and not managed by MEF. Typically we let MEF give us objects it knows thru its container after the catalog has been constructed. In this particular case the catalog may be empty and yet we wanted to add and remove objects from the container.

Here I create an empty catalog and then populate it with an object/part that is created and managed outside MEF. CompositionBatch.AddExportedValue is used to do so. I tried using ComposeExportedValue on the container and had no luck. Debugging .net source showed calling this method goes to SingleComposablePart(?) which does not give object back when asked for export.

To remove an object, RemovePart can be used. Alternatively, instead of using RemovePart, you can use CompositionBatch's contstuctor and specify the second parameter as the part to be removed. Sample Code is shown below: