tags:

views:

59

answers:

4

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.

A: 

Try:

CommandModule = CommandObject as ICommandModule;
Jakub Konecki
+1  A: 

Take Jakub's suggestion and make this change:

ICommandModule CommandModule = Activator.CreateInstance(AsmType) as ICommandModule;

You may have run into a situation where Activator.CreateInstance(AsmType) is returning null. If so, it may be that it found the declaration for the Interface itself and there is no instance creation possible for that particular AsmType. So, when debugging, make sure you know exactly which type you're trying to instantiate.

John Fisher
+1  A: 

You can use Reflection to check whether an object implements a specific interface.

Here's an example:

bool isCommandModule = typeof(ICommandModule).IsAssignableFrom(commandObject);

Related resources:

Enrico Campidoglio
+1  A: 

Your application may be finding the assembly with ICommandModule in two different directories. The assemblies may be exactly the same, but because they are in different directories the type system sees them as different.

Mike Chess
This was the answer to my specific application, however the ones below are all very valid solutions for my question. I'm rebuilding my module interfaces to avoid this problem. Thank you!
kmark937