Reputation: 12498
When our application is running, we want it to occasionally poll for new plugins and load them if it finds any. We don't just want plugins loaded at startup. Is this possible with MEF? We've done it already with reflection, but MEF gives a nice plugin framework and we would like to use it if possible.
Upvotes: 2
Views: 439
Reputation: 12052
You can do it using the DirectoryCatalog class that scans all dll assemblies in a folder. It has also a Refresh method that will rescan the directory and refresh the container if changes are found. This will trigger the ExportsChanged event in the container which contains also information about what changes have occurred.
Here is a very basic sample that demonstrates how to do it:
class Program
{
static void Main(string[] args)
{
DirectoryCatalog catalog = new DirectoryCatalog("plugins", "*.dll");
CompositionContainer container = new CompositionContainer(catalog);
container.ExportsChanged += Container_ExportsChanged;
Console.WriteLine("Copy new plugins and press any key to refresh them.");
Console.ReadKey();
catalog.Refresh();
Console.ReadLine();
}
private static void Container_ExportsChanged(object sender, ExportsChangeEventArgs e)
{
Console.Write("Added Exports: ");
Console.WriteLine(string.Join(", ", e.AddedExports));
}
}
Upvotes: 2