I've been trying to make a module, command-line-like application. Each module can hold multiple commands. For example, "Module A" can have commands like "exit" and "echo". I'm using the following code to load and initialize my modules...
foreach (string Filename in Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Modules"), "*.dll"))
{
Assembly Asm = Assembly.LoadFrom(Filename);
foreach (Type AsmType in Asm.GetTypes())
{
if (AsmType.GetInterface("ICommandModule") != null)
{
object CommandObject = Activator.CreateInstance(AsmType);
ICommandModule CommandModule;
if (CommandObject is ICommandModule)
{
CommandModule = (ICommandModule)CommandObject;
}
else
{
throw new Exception("CommandObject is not a valid ICommandModule.");
}
...
I know for a fact that the module which it is loading (Core.dll) is perfectly in compliance to the ICommandModule interface. When I make sure with if (CommandObject is ICommandModule)
it throws the exception. When I removed the if statement alltogether, it told me it was unable to cast CommandObject
to ICommandModule
.