当我通过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;
}
}
答案 0 :(得分:0)
我想你在问如何阻止所有插件被加载到当前的appdomain中?如果是这样,请使用Assembly.ReflectionOnlyLoadFrom,找到您要查找的插件,并仅在该插件上调用Assembly.Load。