Kevin Mark
Kevin Mark

Reputation: 1671

Implementation of Interface Invalid

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.

Upvotes: 1

Views: 128

Answers (4)

Mike Chess
Mike Chess

Reputation: 2798

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.

Upvotes: 1

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59913

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:

Upvotes: 1

John Fisher
John Fisher

Reputation: 22719

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.

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46008

Try:

CommandModule = CommandObject as ICommandModule;

Upvotes: 0

Related Questions