NullifyNetwork

The blog and home page of Simon Soanes
Skip to content
[ Log On ]

So, I'm playing with reflection with the intention of making a plugin system for future use and looking at the obscenely complex articles on the net that don't cover anything even remotely like what I want to do.  Which is have an object I didn't write, and be able to .DoSomething with it rather than have four lines of garbage to just run a static method.  I wanted to be able to use classes I hadn't referenced at design time, just as if I had.  Obviously they need to follow my interface definition, but that's a small price to pay.

So I eventually give up and go back to the docs and play around for a bit, eventually getting this ludicrously simple method working:

OpenFileDialog openasm = new OpenFileDialog();
if (openasm.ShowDialog() == DialogResult.OK)
{
   Assembly testasm = Assembly.LoadFrom(openasm.FileName);
   Type[] asmtypes = testasm.GetTypes();
   foreach (Type t in asmtypes)
   {
      if (t.IsClass & t.GetInterface("IHiThere")!=null)
      {
         object o = testasm.CreateInstance(t.FullName);
         IHiThere asm = o as IHiThere;
         if (asm != null)
         {
            MessageBox.Show(asm.Hi());
         }
         else
         {
            MessageBox.Show("Failed to make asm = o");
         }
      }
   }
}

A quick rundown, that's:

Load the assembly you want to look at:
Assembly testasm = Assembly.LoadFrom("filename.dll");

Get a list of the types of objects in it:
Type[] asmtypes = testasm.GetTypes();

Loop through it, and for each class that implements your chosen shared interface* create it as an object:
object o = testasm.CreateInstance(t.FullName);

Then cast it to your interface:
IHiThere asm
= o as IHiThere;

Creating it as a local object you can use just like normal:
MessageBox.Show(asm.Hi());

* - Note that the interface in question here looked like:

public interface IHiThere
{
   string
Hi();
}

And was referenced by both the 'plugin' and the 'host' application.

The plugin side was a simple class that implemented the IHiThere interface, and returned "Hellow world from the plugin" as a string in the Hi method:

public class Class1 : IHiThere
{
   public
Class1()
   {
   }
   public
string Hi()
   {
      return
"Hello World - from the plugin";
   }
}

Permalink  1 Comments 

Thanks! by mike at 01/04/2008 15:58:30
Thanks for simplifying what seemed like such a complicated task. This is exactly what I needed for a tool I'm building.