A flexible plugin loader
Ever added plugin capabilities to your application? Are you tired of writing the same discovery and loading code over and over? I am too, and came up with this fun little class:
class PluginLoader { public static ConstructorInfo[] FindPlugins(Type pluginType) { ArrayList list = new ArrayList(); foreach (string file in Directory.GetFiles(Environment.CurrentDirectory, "*.dll")) { try { FileInfo fileInfo = new FileInfo(file); string assemblyPath = fileInfo.Name.Replace(fileInfo.Extension, ""); Assembly asm = AppDomain.CurrentDomain.Load(assemblyPath); foreach (Type t in asm.GetExportedTypes()) { if (pluginType.IsAssignableFrom(t)) { ConstructorInfo ctor = t.GetConstructor(Type.EmptyTypes); if (ctor != null) { list.Add(ctor); } } } } catch (Exception e) { Trace.WriteLine("Exception encountered loading plugin: " + e.ToString()); // this is deliberately ignored, as any error in loading the assembly should just involve // continuing on } } return (ConstructorInfo[])list.ToArray(typeof(ConstructorInfo)); } }
Wherever you want to get a list of available plugins, use PluginLoader.FindPlugins(typeof(YourPluginType));. The method returns an array of ConstructorInfo objects so you will be responsible for instantiating the objects yourself. This is the heavy part of the reflection though, so its only done once and you can instantiate when you need the plugin.
One thing I would probably like to do is to get the discovery mechanism happening in a secondary appdomain. This will help by keeping assemblies unloaded until they are actually used by the application.
I recommend the plugin approach described by this article (http://msdn.microsoft.com/msdnmag/issues/05/07/Reflection/) because it allows an application to start much more quickly. Unfortunately, it’s not as dynamic as the method Matt provides.
Leif: The attribute model is nice too, but if you wanted to best of both worlds (ie: flexibility and startup speed), you could easily queue a worker thread to run the PluginLoader.
What I want to do on my blog, is every few hours take the oldest post and move it to the
front of the queue, all automatically. Anyone know if there is a plugin that can do this or
a simple way to set up another plugin to do this (use my own feed perhaps)?
Thanks.


