This project has moved and is read-only. For the latest updates, please go here.

MEF and C# scripting?

Mar 17, 2010 at 10:43 AM


After a (admittedly short) glance at the docs and the example solution,
I got the impression that MEFsuits best for cases in which plugins are available
at program start.
It is not clear to me whether it is possible to use CSharpCodeProvider et. al. to
compile code in memory and temporarily add the result of compilation to the set
of plugins loaded (and probably executed) by MEF.

Could you please provide some hints how to combine MEF with Scripting?
That would make MEF a very useful tool for me.

Many thanks,




Mar 18, 2010 at 10:22 PM

Hi Markus

You can add new parts dynamically at runtime. To add them to an existing container you'll want to pass in an AggregateCatalog to the container on construction. Hold on to the referrence to the aggregate for later. Whenever you have new parts that you want to add, you can create a new catalog and add it to the aggregate. Once you do it will be visible to the container. We have TypeCatalog and AssemblyCatalog which respectively accept Types and Assemblies. You can use either to add emitted types to the catalog.



Mar 24, 2010 at 10:48 PM
Hi Glenn Thanks for the reply. If I use an AggregateCatalog I am still unsure whether I am able to unregister/remove the loaded parts later (e.g. a script command is to be called exactly once) The docs at e.g. did not give me the information you provided in your answer. I got the impression that all Catalogs must be availbale at construction time. Therefore: Could you please provide some code example? This would make it a lot easier ... Thanks, Markus
Mar 24, 2010 at 10:58 PM

You can remove catalogs or part instances that you specifically add to the container.

OK, here's a sample

var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog("Extensions");
var container = new CompositionConainer(catalog);

//some work with the container

var type = GetSomeDynamicallyEmittedType(); //retrieves an emitted type that has a "Foo" export
var typeCatalog = new TypeCatalog(type);
var dynamic = container.GetExportedValue<object>("Foo");

Above I am grabbing a dynamically emitting type (note: Hand waving here) which has a "Foo" export and then creating a new type catalog with that type which I then add to the aggregate. Once I do that I can now pull on the container to get that type.


Mar 24, 2010 at 11:01 PM

Second part to the post, how to remove. :-)

catalog.Catalogs.Remove(typeCatalog); //removes the catalog

Now the caveat of all of this has to do with recomposition. In order to be able to add new parts to the catalog after the container has been initialized, all importers of those contracts must be recomposable, otherwise the container will throw an exception. In this case because I am manually pulling on the container I am not affected.