I have an application where I'd like to display a list of all plugins located in a specified directory (and sub-directories). This is my first time using MEF and so I'm having some difficulty understanding how the framework works and in what order things need to be done. I think I know what the problem is (more later), but I'm not sure and I'm uncertain in how to fix it.
private CompositionContainer container;
private AggregateCatalog catalog = new AggregateCatalog();
[ImportMany(typeof(IPlugin), AllowRecomposition = true)]
IEnumerable<Lazy<IPlugin, IPluginData>> plugins = null;
private void LoadPlugins(string rootPath)
{
/* release old contents if the refreshTree
* method is called
*/
if (null != plugins)
container.ReleaseExports(plugins);
try
{
TreeNode rootNode = new TreeNode(rootPath);
rootNode.Name = rootPath;
populateTreeView(rootNode.Nodes, rootNode, true);
// add the root node to the TreeView
pluginTreeView.Nodes.Add(rootNode);
container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
catch (CompositionException ex)
{
MessageBox.Show(ex.Message);
}
}
private bool appendToCatalog(string path, bool create, out DirectoryCatalog dirCatalog)
{
dirCatalog = null;
// check that the plugin directory exists
if (false == System.IO.Directory.Exists(path))
{
// do we want to create a directory for it?
if(true == create)
System.IO.Directory.CreateDirectory(path);
return false;
}
// finally, append the plugins to the catalog
dirCatalog = new DirectoryCatalog(path, Constants.Strings.PLUGIN_EXTENSION);
catalog.Catalogs.Add(dirCatalog);
return true;
}
private void populateTreeView(TreeNodeCollection nodes, TreeNode currentNode, bool isRoot)
{
DirectoryCatalog dirCatalog;
if(false == appendToCatalog(currentNode.Name, isRoot, out dirCatalog))
return;
try
{
// get subfolder list
string[] directories = Directory.GetDirectories(currentNode.Name);
//add a new node for each subfolder
foreach (string directory in directories)
{
nodes.Add(directory, Path.GetFileName(directory));
}
// Problem is probably here
foreach (var plugin in plugins)
{
nodes.Add(plugin.Metadata.Name, plugin.Metadata.Name);
}
foreach(TreeNode node in nodes)
populateTreeView(node.Nodes, node, false);
}
catch
{
return;
}
}
Now, here's what I believe the problem is. If you notice in the populateTreeView()
function I have the following comment: // Problem is probably here
. My assumption here is that the plugins have not yet been loaded and therefore the foreach
loop is never executed. But at the same time, I'd like to only load valid plugins (i.e. No dll's from another unrelated project), so I'd rather not display a list of all dll's in the folder.