Jun 5, 2011 08:19 AM
(This post was last modified: Jun 5, 2011 08:25 AM by Venom Page.)
This tutorial teaches you the basics of .NET Reflection and shows how to create a simple Plugin-System based on Assemblies.
I will use C# instead of VB, just because I think it has the superior syntax, but it should translate to any .NET language.
What we're trying to do:
We want to have a Collection of Plugin-Objects which can be dynamically loaded from DLL files and then used as if they were compiled into the main assembly.
We need:
- An interface (duh.)
- A collection for the Plugins
- A function to load a Plugin into the collection.
We need to define our Collection and out Interface:
Note that this interface isn't useful it all and just returns Metadata, you can extend it so it fits your needs.
Next is the function to load plugins:
Sample plugin:
You can now call your plugin-code from the List ;)
I will use C# instead of VB, just because I think it has the superior syntax, but it should translate to any .NET language.
What we're trying to do:
We want to have a Collection of Plugin-Objects which can be dynamically loaded from DLL files and then used as if they were compiled into the main assembly.
We need:
- An interface (duh.)
- A collection for the Plugins
- A function to load a Plugin into the collection.
We need to define our Collection and out Interface:
Code
public static List<IPlugin> plugins = new List<IPlugin>();
public interface IPlugin
{
public Version GetVersion();
public string GetPluginName();
}Next is the function to load plugins:
Code
public static void LoadPlugin(string dllFilename)
{
if (!System.IO.File.Exists(dllFilename))
return;
try
{
var pluginAssembly = Assembly.LoadFrom(dllFilename);
foreach (var type in pluginAssembly.GetTypes())
{
Type pluginType = type.GetInterface("Your.Namespace.IPlugin");
if (pluginType != null)
{
plugins.Add((IPlugin)Activator.CreateInstance(pluginType));
}
}
}
catch (Exception e)
{
throw new Exception("Could not load plugin!", e);
}
}Sample plugin:
Code
´
public class PluginExample : IPlugin
{
public Version GetVersion()
{
return new Version(1, 0, 0, 0);
}
public string GetPluginName()
{
return "ExamplePlugin";
}
}You can now call your plugin-code from the List ;)

