private T LoadPlugin <T>(string dllFileName) { Type interfaceType = typeof(T); try { var pluginPath = Path.Combine(GetPluginFolderPath(), dllFileName); if (!File.Exists(pluginPath)) { pluginPath = Path.Combine(GetPluginFolderPath(usePluginSubfolder: false), dllFileName); } if (File.Exists(pluginPath)) { // https://stackoverflow.com/questions/10732933/can-i-use-activator-createinstance-with-an-interface var pluginAssembly = Assembly.LoadFrom(pluginPath); var exportedTypes = pluginAssembly.GetExportedTypes(); var pluginType = pluginAssembly.GetTypes() .Where(type => type.GetInterfaces() .Any(inter => inter.IsAssignableFrom(interfaceType))) .FirstOrDefault(); var obj = (T)Activator.CreateInstance(pluginType); return(obj); } else { _log?.Warning($"Plugin Load Failed [{interfaceType}] File does not exist: {dllFileName}"); } } catch (ReflectionTypeLoadException ex) { _log?.Warning($"Plugin Load Failed [{interfaceType}] :: {dllFileName} [Reflection or Loader Error]"); _log.Error(ex.ToString()); foreach (var loaderEx in ex.LoaderExceptions) { _log.Error(loaderEx.ToString()); } } catch (Exception exp) { _log?.Error(exp.ToString()); } return(default);
private T LoadPlugin <T>(string dllFileName, Type interfaceType) { try { var pluginPath = GetPluginFolderPath() + "\\" + dllFileName; if (File.Exists(pluginPath)) { // https://stackoverflow.com/questions/10732933/can-i-use-activator-createinstance-with-an-interface var loadedType = (from t in Assembly.LoadFrom(pluginPath).GetExportedTypes() where !t.IsInterface && !t.IsAbstract where interfaceType.IsAssignableFrom(t) select t) .FirstOrDefault(); var obj = (T)Activator.CreateInstance(loadedType); return(obj); } else { _log?.Warning($"Plugin Load Failed [{interfaceType}] File does not exist: {dllFileName}"); } } catch (Exception exp) { _log?.Error(exp.ToString()); } return(default(T)); }