C#_Reflection_Plugin_Templete.cs
using System;
using System.IO;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string pluginFoler = @".\plugin";
if (Directory.Exists(pluginFoler) == true)
{
ProceesPlugin(pluginFoler);
}
}
private static void ProceesPlugin(string rootPath)
{
foreach (string dll in Directory.EnumerateFiles(rootPath, "*.dll"))
{
Assembly plugin = Assembly.LoadFrom(dll);
Type entryType = FindEntryType(plugin);
if (entryType == null)
continue;
object inst = Activator.CreateInstance(entryType);
MethodInfo entryMethod = FindStartupMethod(entryType);
if (entryMethod == null)
continue;
entryMethod.Invoke(inst , null);
}
}
private static Type FindEntryType(Assembly plugin)
{
foreach (Type t in plugin.GetTypes())
{
foreach (object obj in t.GetCustomAttributes(false))
{
if (obj.GetType().Name.Equals("PluginAttribute"))
{
return t;
}
}
}
return null;
}
private static MethodInfo FindStartupMethod(Type entryType)
{
foreach (MethodInfo m in entryType.GetMethods())
{
foreach (object obj in m.GetCustomAttributes(false))
{
return m;
}
}
return null;
}
}
}