private IEnumerable<CommandMetaData> LoadCommandsFromDirectory(DirectoryInfo directory) { AppDomain domain = null; var commands = new List<CommandMetaData>(); foreach (var file in directory.EnumerateFiles("*.dll", SearchOption.TopDirectoryOnly)) { try { var assembly = Assembly.LoadFrom(file.FullName); foreach (var type in assembly.GetExportedTypes()) { if (type.GetInterface("ShellMe.CommandLine.CommandHandling.ICommand") != null && !type.IsAbstract) { if (domain == null) { var domainSetup = new AppDomainSetup() { ApplicationBase = directory.FullName }; domain = AppDomain.CreateDomain("Sandbox Domain", null, domainSetup); } var assemblyName = assembly.FullName; var typeName = type.FullName; var metaData = new CommandMetaData() { Domain = domain, AssemblyName = assemblyName, TypeName = typeName }; var command = CreateCommand(metaData); metaData.Command = command; commands.Add(metaData); } } } catch (Exception e) { // Ignore DLLs that are not .NET assemblies. } } return commands; }
private ICommand CreateCommand(CommandMetaData commandMetaData) { return (ICommand)commandMetaData.Domain.CreateInstanceAndUnwrap(commandMetaData.AssemblyName, commandMetaData.TypeName); }