public class Host : IHost
{
private List plugins = new List();
public List Plugins => plugins;
public int LoadPlugins(string path)
{
string[] files = Directory.GetFiles(path, "*.dll");
foreach (var file in files)
{
Assembly asm = Assembly.LoadFrom(file);
foreach (var type in asm.GetExportedTypes())
{
if (type.IsClass && typeof(ILog).IsAssignableFrom(type))
{
ILog plugin = Activator.CreateInstance(type) as ILog;
plugins.Add(plugin);
}
}
}
return plugins.Count;
}
public ILog GetLog(string name)
{
foreach (var item in plugins)
if (item.GetType().ToString() == name) return item;
return null;
}
}
static void Main()
{
Host host = new Host();
host.LoadPlugins(".");
ILog log = host.GetLog(ConfigurationManager.AppSettings["LogType"]);
log.Write(new Exception("異常測試"));
}
ILog 實作參考前文。此架構展示反射動態載入組件、掃描型別、篩選實作特定介面的類別、實例化並管理外掛的完整流程。