I had a need to scan a directory for assemblies and load (instantiate) a specific interface from the foreign assembly. The idea was that the application would work with a plugin architecture which would allow for an outside foreign assembly to be dropped in. Upon startup, the application would look into the directory and instantiate the plugin via its interface. (Note this is .Net 2 code and .Net 3.5 has a plugin architecture but the concepts of reflection are what are important in this article).

The following code will accept a filename of the assembly and attempt to load the interface in question. If it succeeds it returns the interface:

private IPlugin LoadPlugin( string AssemblyFileName )
{
 IPlugin PluginFound = null;
 Type iPluginType = typeof(IPlugin);

 Assembly _Assembly = Assembly.LoadFrom(AssemblyFileName);

 if (_Assembly != null)
 {
   Type[] types = _Assembly.GetExportedTypes();

   foreach (Type t in types)
    if (iPluginType.IsAssignableFrom(t))
    {
     IPlugin operation = Activator.CreateInstance(t) as IPlugin;

     if (operation != null) // Found!
     {
       PluginFound = operation;
       break;
     }
    }
   }

   return PluginFound;
  }
}

Here is what is going on:

  • Line 1 : The fully qualified filename is passed into the method.
  • Line 3 : The instantiated object if found, to be returned in this reference.
  • Line 4 : The actual type we are interested in.
  • Line 10 : Reflect the types found in the foreign assembly.
  • Line 13 : Is the current type the same as what we are looking for?
  • Line 15 : Try creating an instance.
  • Line 17 : Test the cast from line 15. If it is not null. We have a valid instance.
Share

Tags: , , ,