Created
July 11, 2016 07:57
-
-
Save JohnBaek/b0bb607d7c21edd93763f40416cce550 to your computer and use it in GitHub Desktop.
C#_Reflection_Plugin_Templete.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment