Say, your application name is App
. Within a Solution do:
- Change Assembly name to
App.Plugin
- Change Default namespace to
App
- Create an new abstract class named
Plugin
:
namespace App {
public abstract class Plugin {
public virtual void DoSomething() {
}
}
}
- Show All Files
- Create new directory
bin\Debug\Plugins
-- This is thePlugins
directory - Add reference to
Plugin
- 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();
}
}
}
- Build the project
- Change Output path (in Project Properties > Build > Output) to point to
Plugins
directory. - Change Start Action (in Project Properties > Debug) to Start external program that points to
App.exe
- Change Working Directory (in Project Properties > Debug > Start Options) to point to
App.exe
directory. - Add reference to
Plugin
. Set Copy Local to False - Add
App
as Project Dependencies - Create a new class named
HelloWorldPlugin
:
namespace HelloWorldPlugin {
public class HelloWorldPlugin : App.Plugin {
public override void DoSomething() {
Console.WriteLine("Hello world!");
}
}
}
- Set as StartUp Project
- Start debuggging
HelloWorldPlugin -> Plugin
\ ^
\ |
+-> App