July 15, 2010

Generic Dynamic Class Factory (.net)

This code provides a simple way to dynamically load all the assemblies in a directory (by default the bin directory in your project)
using System.Text;
using System.Reflection;
using System.IO;
public class DynamicFactory {
   List allAssemblies = new List();
   public DynamicFactory() { }
   public void LoadAssemblies() {
       Assembly thisAssembly = Assembly.GetExecutingAssembly();
       Uri thisUri = new Uri(thisAssembly.CodeBase);
       string path = Path.GetDirectoryName(thisUri.LocalPath);
       LoadAssemblies(path);
   }
   public void LoadAssemblies(string path) {
       allAssemblies.Clear();
       foreach (string dll in Directory.GetFiles(path, "*.dll")) {
           allAssemblies.Add(Assembly.LoadFile(dll));
       }
   }
   public IEnumerable EnumerateTypes() {
       foreach (var assembly in allAssemblies) 
           foreach (Type type in assembly.GetExportedTypes())
               if (typeof(T).IsAssignableFrom(type))
                   yield return type;                               
   }
   public IEnumerable EnumerateObjects() {
       foreach (var assembly in allAssemblies)
           foreach (Type type in assembly.GetExportedTypes())
               if (typeof(T).IsAssignableFrom(type))
                   yield return (T)Activator.CreateInstance(type);
   }
}