我编写了一个小型测试应用程序来演示我要解决的问题。我有一个插件架构,其中插件派生自一个接口(interface)。
接口(interface)代码如下:
namespace Test
{
public interface ITestBase
{
int LifeTheUniverseAndEverything();
bool Pessimist();
bool Optimist();
}
}
这将生成一个 .dll,该 dll 被主程序解决方案和插件解决方案引用。
插件代码如下:
namespace Test
{
public class TestPlugin : ITestBase
{
public int LifeTheUniverseAndEverything() { return 41; }
public bool Pessimist() { return false; }
public bool Optimist() { return true; }
}
}
这会生成一个 .dll,它被放入主工作目录外的“插件”文件夹中。
这是主程序。
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("testing...");
string[] PluginFileLocs;
try
{
string sWorkingDir = Directory.GetCurrentDirectory();
string sPluginDir = sWorkingDir + "\\Plugins";
PluginFileLocs = Directory.GetFiles(sPluginDir, "*.dll");
foreach (string plugin in PluginFileLocs)
{
Assembly theAssembly = Assembly.ReflectionOnlyLoadFrom(plugin);
foreach (Type type in theAssembly.GetTypes())
{
string aType = type.FullName;
Console.WriteLine(aType);
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
}
问题是,如果 testplugin 类派生自 ITestBase 接口(interface),theAssembly.GetTypes 会抛出异常:无法加载一个或多个请求的类型。检索 LoaderExceptions。为什么以及如何让我的插件派生出一个接口(interface)?
请您参考如下方法:
根据 Assembly.ReflectionOnlyLoadFrom 的文档,它不会自动加载依赖项 http://msdn.microsoft.com/en-us/library/system.reflection.assembly.reflectiononlyloadfrom.aspx
我猜这就是这里发生的事情。由于您的接口(interface)是在与插件分开的程序集中定义的,因此您必须先加载该程序集,然后再尝试调用 GetTypes。
