How to create a DirectoryCatalog that will search sub directories for plugins

3k views Asked by At

So I have my directory catalog set up shown below:

DirectoryCatalog directoryCatalog = new DirectoryCatalog(@".\Plugins");
var catalog = new AggregateCatalog(directoryCatalog);
var container = new CompositionContainer(catalog);
container.ComposeParts(this);

Which will find any .dll's in my Plugins folder that meet my import criteria. Now To prevent reference clashes in my plugins I would like to put each plugin in a seperate folder.

e.g.

Plugins -> Plugin1 -> plugin1.dll

      -> Plugin2 -> plugin2.dll

But my DirectoryCatalog doesn't find these plugins. Is it possible to implement this or do my plugin libraries have to be in that specified .\Plugins folder

2

There are 2 answers

0
Igor On BEST ANSWER

You can solve your problem by adding multiple DirectoryCatalogs to AggregateCatalog.Catalogs property like this:

var catalog = new AggregateCatalog();
// iterate over all directories in .\Plugins dir and add all Plugin* dirs to catalogs
foreach (var path in Directory.EnumerateDirectories(@".\Plugins", "Plugin*", SearchOption.TopDirectoryOnly))
{
    catalog.Catalogs.Add(new DirectoryCatalog(path));
}

_container = new CompositionContainer(catalog);
this._container.ComposeParts(this);
0
Iain Ballard On

There is also this: https://github.com/MefContrib/MefContrib/blob/master/src/MefContrib/Hosting/RecursiveDirectoryCatalog.cs

I found I needed to wrap the _aggregateCatalog.Catalogs.Add(catalog); under Initialize(...) with a try/catch for ReflectionTypeLoadException to stop it throwing when it found non-plugin dlls.