插件体系结构 - 在运行时加载程序集时出错

时间:2013-03-25 14:11:58

标签: c# reflection

我写了一个有抽象类的应用程序。我想支持这个类的实现作为插件。

这是抽象类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace Stub.Logic {
    public abstract class Connection {
        …stuff
    }
}

这是一个实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using Stub.Logic;

namespace MqConnection {
    public class MqConnection : Connection {
        …stuff
    }
}

将插件放在一个可以读取和加载的文件夹中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace Stub.Logic {
    public class PluginManager {
        private static List<Type> connectionTypes = new List<Type>();

        public static void LoadConnectionTypes(string path) {
            DirectoryInfo dllDirectory = new DirectoryInfo(path);
            FileInfo[] dlls = dllDirectory.GetFiles("*.dll");
                foreach (FileInfo dllFileInfo in dlls) {
                    try {
                        Assembly assembly = Assembly.LoadFrom(dllFileInfo.FullName);
                        connectionTypes.AddRange(**assembly.GetTypes()**);
                    } catch (Exception ex) {
                        if (ex is System.Reflection.ReflectionTypeLoadException) {
                        var typeLoadException = ex as ReflectionTypeLoadException;
                        var loaderExceptions = typeLoadException.LoaderExceptions;
                        TextWriter writer = new StreamWriter(@"C:\Users\yoav.benzvi\Desktop\error.txt");
                        writer.WriteLine(loaderExceptions[0].ToString());
                        writer.Close();
                    }
                }
            }
        }
    }
}

它在assembly.GetTypes()调用失败。这是我得到的错误:

  

System.IO.FileNotFoundException:无法加载文件或程序集   'StubLogic,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'或   其中一个依赖项。该系统找不到指定的文件。   文件名:'StubLogic,Version = 1.0.0.0,Culture = neutral,   公钥=空'

我是否需要在插件文件夹中安装StubLogic.dll?因为它已经是应用程序的一部分,所以似乎是多余的,所以我做错了什么?

编辑:添加参考属性:
enter image description here

编辑2:向所有人道歉。代码正在运行。问题出在我糟糕的测试中。再次向在这里浪费时间的人道歉。

3 个答案:

答案 0 :(得分:1)

确保插件引用了您拥有的相同版本的StubLogic程序集,或者插件程序集项目中StubLogic引用的“使用特定版本”为false。

答案 1 :(得分:1)

我建议你这个代码

我用

修改了你的路径
DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "YourDirectoryRepository"));

所以

 DirectoryInfo dInfo = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "YourDirectoryRepository"));
 FileInfo[] files = dInfo.GetFiles("*.dll");
 List<Assembly> plugInAssemblyList = new List<Assembly>();

 if (null != files)
 {
      foreach (FileInfo file in files)
      {
           plugInAssemblyList.Add(Assembly.LoadFrom(file.FullName));
      }
 }

答案 2 :(得分:0)

向所有人道歉。代码正在运行。问题是我的测试不好。再次向在这里浪费时间的人道歉。

相关问题