Skip to content

Instantly share code, notes, and snippets.

@audinue
Last active May 15, 2017 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/04747bf9c1e4da18274b34809f4118bd to your computer and use it in GitHub Desktop.
Save audinue/04747bf9c1e4da18274b34809f4118bd to your computer and use it in GitHub Desktop.
C# Plugin System with Visual Studio

C# Plugin System with Visual Studio

Say, your application name is App. Within a Solution do:

1. Create a new Class Library project named Plugin

  1. Change Assembly name to App.Plugin
  2. Change Default namespace to App
  3. Create an new abstract class named Plugin:
namespace App {
  public abstract class Plugin {
    public virtual void DoSomething() {
    }
  }
}

2. Create a new Console Application named App

  1. Show All Files
  2. Create new directory bin\Debug\Plugins -- This is the Plugins directory
  3. Add reference to Plugin
  4. Edit Program.cs:
namespace App {
  class Program {
    static void Main(string[] args) {
      // Load plugins in parallel
      var plugins = Directory.GetFiles(
          Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"),
          "*.dll"
        )
        .AsParallel()
        .Select(file => Assembly.LoadFile(file))
        .SelectMany(assembly => assembly.GetTypes())
        .Where(type => type.IsSubclassOf(typeof(Plugin)))
        .Select(type => Activator.CreateInstance(type) as Plugin)
        .ToList();
      // Do whatever you like with `plugins`.
      // For example:
      foreach(var plugin in plugins) {
        plugin.DoSomething();
      }
      Console.ReadLine();
    }
  }
}
  1. Build the project

3. Create a new Class Library project named HelloWorldPlugin

  1. Change Output path (in Project Properties > Build > Output) to point to Plugins directory.
  2. Change Start Action (in Project Properties > Debug) to Start external program that points to App.exe
  3. Change Working Directory (in Project Properties > Debug > Start Options) to point to App.exe directory.
  4. Add reference to Plugin. Set Copy Local to False
  5. Add App as Project Dependencies
  6. Create a new class named HelloWorldPlugin:
namespace HelloWorldPlugin {
  public class HelloWorldPlugin : App.Plugin {
    public override void DoSomething() {
      Console.WriteLine("Hello world!");
    }
  }
}
  1. Set as StartUp Project
  2. Start debuggging

Project dependency graph

HelloWorldPlugin -> Plugin
              \       ^
               \      |
                +->  App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment