如何获得单个泛型类型而不是整个集合

时间:2016-07-13 13:33:57

标签: c# generics plugins types mef

当我通过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;
    }
}

1 个答案:

答案 0 :(得分:0)

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