MEF recursive plugin search
Asked Answered
S

4

14

Let's say that I have a few applications in a folder (each application has subfolders where plugins can be located):

  • Clients
    • Application A
      • ...
    • Application B
      • ...
    • Application C
      • ...
    • ...

Some files in these applications have an Export-attribute applied, others don't. Now, I want to be able to load these plugins in some of these applications. Is there a proper way to let MEF search recursively in every subfolder of a specified folder?

Saskatchewan answered 15/11, 2011 at 15:35 Comment(0)
B
17

No, you will need to recurse through the directories yourself creating a DirectoryCatalog for each. Then, combine all of the DirectoryCatalogs with an AggregateCatalog to create the container.

Bernadette answered 15/11, 2011 at 17:24 Comment(0)
S
2

Another way is to get all the DLL files under a specified directory (recursively) and load them one by one using the assembly catalog.`

var catalog = new AggregateCatalog();

        var files = Directory.GetFiles("Parent Directory", "*.dll", SearchOption.AllDirectories);

        foreach (var dllFile in files)
        {

            try
            {
                var assembly = Assembly.LoadFile(dllFile);
                var assemblyCatalog = new AssemblyCatalog(assembly);
                catalog.Catalogs.Add(assemblyCatalog);
            }
            catch (Exception e)
            {
               // this happens if the given dll file is not  a .NET framework file or corrupted.

            }
        }
Sleuthhound answered 9/4, 2015 at 12:27 Comment(0)
O
1

There's a MEFContrib project available that has a RecursiveDirectoryCatalog for just this purpose...

https://www.nuget.org/packages/MefContrib/

Oxus answered 1/7, 2014 at 4:26 Comment(0)
V
1

I created an implementation based in Nicholas Blumhardt answer, I hope that code helps others in future.

private void RecursivedMefPluginLoader(AggregateCatalog catalog, string path)
{
    Queue<string> directories = new Queue<string>();
    directories.Enqueue(path);
    while (directories.Count > 0)
    {
        var directory = directories.Dequeue();
        //Load plugins in this folder
        var directoryCatalog = new DirectoryCatalog(directory);
        catalog.Catalogs.Add(directoryCatalog);

        //Add subDirectories to the queue
        var subDirectories = Directory.GetDirectories(directory);
        foreach (string subDirectory in subDirectories)
        {
            directories.Enqueue(subDirectory);
        }
    }
}
Vagal answered 15/4, 2016 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.