带有接口的插件架构;接口检查不起作用
-
13-09-2019 - |
题
我正在应用程序中实现一个简单的插件架构。插件要求是使用应用程序和插件引用的 *.dll 中的接口 (IPlugin) 定义的。该应用程序有一个插件管理器(也在同一个 *.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
}
}
}
我曾经测试过一个特定的类名(“插件”),但后来我允许它循环遍历程序集中的所有类,但无济于事。(这是我在其他地方发现的一个示例。)要使它更加复杂,每个接口都实现了原始接口(iplugina,ipluginb)。该插件实际上实现了更具体的接口之一(IPluginB)。但是,我已经尝试使用仅实现更通用的接口(IPlugin)的插件,但这仍然不起作用。
[编辑:为了响应我首次收到的两个响应]是的,我尝试使用issignable From。请参阅以下内容:
Assembly pluginAssembly = Assembly.LoadFrom(currFile.FullName);
if (pluginAssembly != null)
{
foreach (Type currType in pluginAssembly.GetTypes())
{
if (typeof(IPlugin).IsAssignableFrom(currType))
{
string test = "test";
}
}
}
解决方案
你有没有尝试过:
typeof(IPlugin).IsAssignableFrom(currType)
另外,类型 实施 接口,但它们没有 派生 从他们。这 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();
}
其他提示
方法IsAssignableFrom是你在找什么:
Type intType = typeof(IInterface);
foreach (Type t in pluginAssembly.GetTypes())
{
if (intType.IsAssignableFrom(t))
{
}
}
不隶属于 StackOverflow