带接口的插件架构; 接口检查不起作用

Tim*_*Tim 2 c# interface plugin-architecture

我在应用程序中实现了一个简单的插件架构.插件要求是使用接口(IPlugin)定义的,该接口位于应用程序和插件引用的*.dll中.该应用程序有一个插件管理器(也在同一个*.dll中),它通过查找插件文件夹中的所有*.dll加载插件,加载它们,然后检查插件是否实现了接口.我已经通过两种不同的方式检查了[以前通过一个简单的if(插件是IPlugin)],但是当插件实现接口时,都不会识别.这是代码:

Assembly pluginAssembly = Assembly.LoadFrom(currFile.FullName);
if (pluginAssembly != null)
{
    foreach (Type currType in pluginAssembly.GetTypes())
    {
        if (currType.GetInterfaces().Contains(typeof(IPlugin)))
        {
            // Code here is never executing
            // even when the currType derives from IPlugin
        }
    }                    
}
Run Code Online (Sandbox Code Playgroud)

我曾经测试过一个特定的类名("插件"),但后来我允许它循环遍历程序集中的所有类都无济于事.(这是我在其他地方找到的一个例子.)为了使这更复杂一点,有两个接口,每个接口实现原始接口(IPluginA,IPluginB).该插件实际上实现了一个更具体的接口(IPluginB).但是,我已经尝试使用插件只是实现更通用的接口(IPlugin),这仍然无法正常工作.

[编辑:回应我第一次收到的两个回复]是的,我尝试过使用IsAssignableFrom.请参阅以下内容:

Assembly pluginAssembly = Assembly.LoadFrom(currFile.FullName);
if (pluginAssembly != null)
{
    foreach (Type currType in pluginAssembly.GetTypes())
    {
        if (typeof(IPlugin).IsAssignableFrom(currType))
        {
            string test = "test";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*ell 5

你有没有尝试过:

typeof(IPlugin).IsAssignableFrom(currType)
Run Code Online (Sandbox Code Playgroud)

此外,类型实现接口,但它们不是从它们派生的.该BaseType属性和IsSubclassOf方法显示推导,其中IsAssignableFrom显示派生或实现.

编辑:您的程序集是否已签名?它们可以装载并排版本的装配,并且由于Type对象与之比较ReferenceEquals,两个并排装配中的相同类型将完全独立.

编辑2:试试这个:

public Type[] LoadPluginsInAssembly(Assembly otherAssembly)
{
    List<Type> pluginTypes = new List<Type>();
    foreach (Type type in otherAssembly.GetTypes())
    {
        // This is just a diagnostic. IsAssignableFrom is what you'll use once
        // you find the problem.
        Type otherInterfaceType =
            type.GetInterfaces()
            .Where(interfaceType => interfaceType.Name.Equals(typeof(IPlugin).Name, StringComparison.Ordinal)).FirstOrDefault();

        if (otherInterfaceType != null)
        {
            if (otherInterfaceType == typeof(IPlugin))
            {
                pluginTypes.Add(type);
            }
            else
            {
                Console.WriteLine("Duplicate IPlugin types found:");
                Console.WriteLine("  " + typeof(IPlugin).AssemblyQualifiedName);
                Console.WriteLine("  " + otherInterfaceType.AssemblyQualifiedName);
            }
        }
    }

    if (pluginTypes.Count == 0)
        return Type.EmptyTypes;

    return pluginTypes.ToArray();
}
Run Code Online (Sandbox Code Playgroud)