C# plugin system
im trying to build a simple plugin system, but im having some issues. i have an abstract class that all plugin classes need to inherit from. once a plugin is built it will be put into a directory for the program to pull from. i can search the directory from the program to find the dlls and i can load their assembly.
the problem that i am having is that i cannot figure out how to create an instance of that plugin class. its very easy when you know the name of the class, but how do you do it when you dont know the name of the class?
thanks
-adam
Load the assembly, iterate the types and find the ones that inherit your base class. Then just use activator to create an instance.
There's also the Managed Extensibility Framework that is semi-official on codeplex. You put attributes on the classes you're using as a plugin, and then use the framework to search for classes with the particular metadata you want.
i appreciate the help you have provided me so far. im still having a bit of a problem though.
here are my base classes, and the derived classes:
here is my experiment code that loads the dlls:
am i doing something wrong to cause the crashing?
thanks
-Adam
here are my base classes, and the derived classes:
public class CommonBase { public virtual void DoStuff() { Console.WriteLine("BaseClass - DoStuff()"); } } public class BaseClass : CommonBase { public override void DoStuff() { Console.WriteLine("CommonBase - DoStuff()"); } }public class Class2 : CommonBase { public override void DoStuff() { Console.WriteLine("Class2"); } }public class Class1 : BaseClass { public override void DoStuff() { Console.WriteLine("Class1"); } }
here is my experiment code that loads the dlls:
string currentDirectory = Directory.GetCurrentDirectory();string[] libraries = Directory.GetFiles(currentDirectory, "*.dll");CommonBase baseClass;Console.WriteLine("CurrentDirectory: " + currentDirectory);foreach (string s in libraries){ Console.WriteLine(s); Assembly a = Assembly.LoadFile(s); Type[] types = a.GetTypes(); foreach (Type t in types) { if (t.BaseType == typeof(CommonBase)) { Console.WriteLine(t.FullName + " is a type of CommonBase"); baseClass = (CommonBase)a.CreateInstance("CommonBase"); baseClass.DoStuff(); // crashes here because baseClass is null } Console.WriteLine(); }}
am i doing something wrong to cause the crashing?
thanks
-Adam
You pass "CommonBase" string instead of the actual type you want to instantiate.
Pass the type you found (t), not a string.
Pass the type you found (t), not a string.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement