public class PlugLoader
{
private List<Assembly> pAssembly = new List<Assembly>();
public Assembly LoaderDLL(string DllPath)
{
try
{
Assembly assembly = null;
if (File.Exists(DllPath))
{
List<Assembly> pSearch = pAssembly.Select((c) => { return (c.Modules.Count() > 0 ? c.Modules.ToList()[0].Name : "") == DllPath ? c : null; }).ToList();
if (pSearch.Count == 0)
{
assembly = Assembly.LoadFrom(DllPath);
pAssembly.Add(assembly);
}
else
{
assembly = pSearch.First();
}
}
return assembly;
}
catch
{
return null;
}
}
public T LoadLibrary<T>(string DllPath) where T : class
{
Assembly assembly = LoaderDLL(DllPath);
if (assembly == null)
return null;
Type type = null;
Type pFindType = typeof(T);
foreach (Type pType in assembly.GetTypes())
{
Boolean bInterface = pFindType.IsAssignableFrom(pType);
if ((pType is T) || bInterface)
{
type = pType;
break;
}
}
if (type == null)
return null;
T tVar = assembly.CreateInstance(type.FullName) as T;
return tVar;
}
}
附上测试代码
public interface IPlug
{
void ShowForm();
}
public partial class Form1 : Form, IPlug
{
public Form1()
{
InitializeComponent();
}
public void ShowForm()
{
this.ShowDialog();
}
}
PlugLoader pLoader = new PlugLoader();
IPlug pPlug = pLoader.LoadLibrary<IPlug>("TestLib.dll");
//pPlug.ShowForm();
IPlug pPlug1 = pLoader.LoadLibrary<IPlug>("TestLib.dll");
pPlug1.ShowForm();