1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/// <summary> /// Load application plugins from folder /// </summary> /// <returns></returns> private static List<Plugin> LoadPlugins() { var pluginTypes = new List<Plugin>(); var pluginFolder = Path.Combine(Environment.CurrentDirectory, "plugins"); foreach (var pluginFile in Directory.GetFiles(pluginFolder, "*.dll")) { Assembly pluginAssembly = Assembly.LoadFile(pluginFile); foreach (var type in pluginAssembly.GetTypes()) { //calls type.IsAssignableFrom to check type implements interface if (!Plugin.ImplementsInterface(type)) continue; //creates an instance of type using reflection pluginTypes.Add(Plugin.CreatePlugIn(type)); break; } } return pluginTypes; }
Refactorings
No refactoring yet !
petar.petrov.myopenid.com
April 23, 2009, April 23, 2009 07:14, permalink
Your code is just fine. Why do you want to use LINQ ? :)
Why not returning IEnumerable<Plugin> ?
However I have one thing to point out - not every DLL is a .NET assembly ;) You can add a try/catch but if you are absolutely sure that there's only .NET assemblies it's OK.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
public static IEnumerable<Plugin> LoadPlugins() { var pluginFolder = Path.Combine(Environment.CurrentDirectory, "plugins"); foreach (var pluginFile in Directory.GetFiles(pluginFolder, "*.dll")) { var pluginAssembly = Assembly.LoadFile(pluginFile); var plugins = from type in pluginAssembly.GetTypes() where Plugin.ImplementsInterface(type) select Plugin.CreatePlugIn(type); var plugin = plugins.FirstOrDefault(); if (plugin != null) { yield return plugin; } } }
anonymous
July 22, 2009, July 22, 2009 13:27, permalink
Hi, what about this implementation? I am not sure about it at all, never used LINQ before, but woudln't that also work? I am also not sure, what the original function should return, since it is called LoadPlugins, but due to the break in the last foreach it allways returns a list with only one element. Therefore this two possibilities ...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/// <summary> /// Load all application plugins from the current folder /// </summary> static IList<Plugin> LoadPlugins() { return IList<Plugin> plugins = from file in Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "plugins"), "*.dll") where Plugin.ImplementsInterface(Assembly.LoadFile(file.GetType())) select Plugin.CreatePlugIn(file.GetType()); } /// <summary> /// Load the first application plugin from the current folder /// </summary> static Plugin LoadFirstPlugins() { return Plugin = (from file in Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "plugins"), "*.dll") where Plugin.ImplementsInterface(Assembly.LoadFile(file.GetType())) select Plugin.CreatePlugIn(file.GetType())).FirstOrDefault(); }
I'm not having any problems with the code, i'd just like to see if it can be refactored any more. Using LINQ perhaps?