using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Pilz.Plugins { public class PluginManager where TPluginInterface : class where TPluginRuntimeInfo : PluginRuntimeInfo { public static IEnumerable LoadPlugins(string[] paths) { var states = new List(); foreach (string path in paths) states.Add(LoadPlugin(path)); return states; } public static TPluginRuntimeInfo LoadPlugin(string path) { var info = Activator.CreateInstance(); var irmplugin = typeof(TPluginInterface); var loadContext = new PluginLoadContext(path); Assembly? assembly = null; if (File.Exists(path)) { try { assembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(path))); } catch { info.Status = PluginStatus.ErrorAtLoading; } } else info.Status = PluginStatus.FileNotFound; if (assembly != null) { foreach (var type in assembly.GetTypes()) { if (info.Plugin == null && irmplugin.IsAssignableFrom(type)) { try { if (Activator.CreateInstance(type) is TPluginInterface plugin) { info.Plugin = plugin; info.Status = PluginStatus.Success; } } catch { info.Status = PluginStatus.ErrorAtInitializing; } } } if (info.Plugin == null) info.Status = PluginStatus.NoValidPlugin; } return info; } } }