Hack Forums
[.NET] [Tutorial] Plugin System for your App - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [.NET] [Tutorial] Plugin System for your App (/showthread.php?tid=1352590)



[Tutorial] Plugin System for your App - Venom Page - Jun 5, 2011

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:

Code
public static List<IPlugin> plugins = new List<IPlugin>();

public interface IPlugin
  {
    public Version GetVersion();
    public string GetPluginName();
  }
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:
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 ;)


* - IllBeBackSoon - Jun 6, 2011

Hey, I'm glad you like it here on HF. Enjoy it Alex.