我编写了一个灵感来自NotePad.NET的插件系统,这个插件系统读取给定文件夹中的所有DLL文件,如果它们使用反射匹配我的接口,则在运行时加载它们。代码在下面
foreach (string file in System.IO.Directory.GetFiles(dir + "\\plugins\\", "*.dll", System.IO.SearchOption.AllDirectories))
if (file.EndsWith(".dll"))
{
Assembly dll = Assembly.LoadFrom(file);
foreach (Type t in dll.GetTypes())
{
try
{
log.WriteLine("Trying to match " + t.BaseType.FullName + " with " + typeof(Acoustical.PluginBase.FileFormatBase).FullName + " and " + typeof(Acoustical.PluginBase.ReportBase).FullName);
if (t.BaseType.FullName == typeof(FileFormatBase).FullName)
{
log.WriteLine(" we compare for " + t.BaseType.FullName);
try
{
fileformatPlugin.Add((dynamic)Activator.CreateInstance(t));
}
catch (Exception ex)
{
log.WriteLine("Error in loading File Plugin ::" + ex.Message + "\r\n" + ex.StackTrace);
}
continue;
}
else if (t.BaseType.FullName == typeof(ReportBase).FullName)
{
log.WriteLine(" we compare for " + t.BaseType.FullName);
reportPlugin.Add((dynamic)Activator.CreateInstance(t));
continue;
}
}
catch (Exception ex) {
log.WriteLine("Error in loading Plugin ::" + ex.Message + "\r\n" + ex.StackTrace);
}
}
dll = null;
}
上面的代码显示了迭代文件夹中所有找到的文件而不是加载它们的部分。
如果我使用Windows窗体或WCF界面应用程序,上面的代码适用于我,它适用于Windows服务但不保证。重新编译时60-70%的时间没有加载插件,然后我在10-15次尝试之后有时加载插件或者有时只加载1-2个插件。
如你所见,我在几乎所有行上都设置了Try catch来跟踪错误发生的位置,但没有出现错误。由于它是Windows SErvice,因此在ONStartup事件上编写此代码时无法进行调试。
我确实在日志中看到了“我们比较”这一行,但是当我们试图看到fileformatplugin得到任何元素时,它的计数保持为0并且日志中没有错误行。
有什么建议吗?