Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

.NET 

[Tutorial] Plugin System for your App

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 ;)
Hey, I'm glad you like it here on HF. Enjoy it Alex.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by BarretNov 11, 2017 09:53 AM 3 374 Nov 11, 2017 09:53 AM
Last Post: StaPol
[C#] by OmegaCodeMay 3, 2016 04:32 PM 1 195 May 3, 2016 04:32 PM
Last Post: pr0t0typ3
[C#] by Ki‎d‎'sJan 17, 2016 06:24 AM 46 9,343 Jan 17, 2016 06:24 AM
Last Post: Rawrrasaurus