This project provides two things:
So the first thing you need to do is define the interface that plugins will implement.
public
interface
IPluginBase
{
string
Name {
get
; }
Version {
}
IMath : IPluginBase
int
Compute(
arg1,
arg2);
namespace
PluggableApplication.Interface
using
System;
System.IO;
System.Reflection;
System.Linq;
static
class
Plugin
T CreatePlugin<T>(
file) {
T plugin =
default
(T);
Type pluginType =
null
;
if
(File.Exists(file))
Assembly asm = Assembly.LoadFile(file);
(asm !=
)
for
(
i = 0; i < asm.GetTypes().Length; i++)
Type type = (Type)asm.GetTypes().GetValue(i);
(IsImplementationOf(type,
typeof
(IPluginBase)))
plugin = (T)Activator.CreateInstance(type);
return
plugin;
private
bool
IsImplementationOf(Type type, Type @
Type[] interfaces = type.GetInterfaces();
interfaces.Any(current => IsSubtypeOf(
ref
current, @
));
IsSubtypeOf(
Type a, Type b)
(a == b)
true
(a.IsGenericType)
a = a.GetGenericTypeDefinition();
false
Math : IMath
"Math"
"1.0.0.0"
arg2) {
arg1 * arg2;
PluggableApplication.Host
PluggableApplication.Interface;
Program
void
Main(
[] args) {
filePath = Environment.CurrentDirectory + @
"\PluggableApplication.Plugin.dll"
IMath math = Plugin.CreatePlugin<IMath>(filePath);
Console.WriteLine();
(math !=
Console.Write(
" Input the 1st number to compute: "
);
arg1 = Convert.ToInt32(Console.ReadLine());
" Input the 2nd number to compute: "
arg2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(
" Results: "
+ math.Compute(arg1, arg2));
else
" No plugins were found."
Console.ReadKey(
Ed Price - MSFT edited Revision 1. Comment: Title casing
very good ;)