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.
Asked
Active
Viewed 337 times
2
-
See if [this](https://stackoverflow.com/a/13253934/587690) helps. – Suresh Feb 24 '20 at 20:07
-
Thanks @sthotakura. I want to know if I can load them dynamically though...not just at startup. – richard Feb 24 '20 at 21:38
1 Answers
2
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));
}
}

Aleš Doganoc
- 11,568
- 24
- 40
-
Thanks @AlesD. Do you know how it reacts to loading newer versions of the same dll? – richard Feb 26 '20 at 22:32
-
I does not work because it is the same namespace. It could work if you manage to remove the previous assembly. In my sample I could not delete the file because it gets locked. Check the following links for more details. [Unloading a dll file in mef](https://stackoverflow.com/questions/9494895/unloading-a-dll-file-in-mef) [MEF and AppDomain - Remove Assemblies On The Fly](https://www.codeproject.com/Articles/633140/MEF-and-AppDomain-Remove-Assemblies-On-The-Fly) – Aleš Doganoc Feb 28 '20 at 00:13