【问题标题】:how to get single generic type instead of entire collection如何获得单个泛型类型而不是整个集合
【发布时间】:2016-07-13 13:33:57
【问题描述】:

当我通过 OpenFile 加载 DLL 时,整个插件集合都被加载到程序集中。我只需要它使用在IPlugin 接口中设置的字符串名称来加载单个插件。

如何让它只加载我想要加载的特定插件?

public static class GenericPluginLoader<T>
{
    public static ICollection<T> LoadPlugins(string path)
    {
        string[] dllFileNames = null;

        if(Directory.Exists(path))
        {
            dllFileNames = Directory.GetFiles(path, "*.dll");

            ICollection<Assembly> assemblies = new List<Assembly>(dllFileNames.Length);
            foreach(string dllFile in dllFileNames)
            {
                AssemblyName an = AssemblyName.GetAssemblyName(dllFile);
                Assembly assembly = Assembly.Load(an);
                assemblies.Add(assembly);
            }

            Type pluginType = typeof(T);

           // Type pluginType = .GetType();
            ICollection<Type> pluginTypes = new List<Type>();
            foreach(Assembly assembly in assemblies)
            {
                if(assembly != null)
                {
                    Type[] types = assembly.GetTypes();

                    foreach(Type type in types)
                    {
                        if(type.IsInterface || type.IsAbstract)
                        {
                            continue;
                        }
                        else
                        {
                            if(type.GetInterface(pluginType.FullName) != null)
                            {
                                pluginTypes.Add(type);
                            }
                        }
                    }
                }
            }

            ICollection<T> plugins = new List<T>(pluginTypes.Count);
            foreach(Type type in pluginTypes)
            {
                T plugin = (T)Activator.CreateInstance(type);
                plugins.Add(plugin);
            }

            return plugins;
        }

        return null;
    }
}

【问题讨论】:

    标签: c# generics plugins types mef


    【解决方案1】:

    我想你是在问如何防止所有插件被加载到当前的 appdomain 中?如果是这样,请使用 Assembly.ReflectionOnlyLoadFrom,找到您要查找的插件,然后仅在该插件上调用 Assembly.Load。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 2015-12-28
      • 2012-08-05
      • 1970-01-01
      相关资源
      最近更新 更多