【发布时间】:2016-08-26 16:25:36
【问题描述】:
我需要加载一个 DLL 和依赖项。在我的数据库中,我已经保存了所有依赖项(引用文件的路径)。
IE:
要加载的DLL:
- id:1
- 名称:“DummyModule.dll”
依赖关系:
- DLL ID:1
- 路径:“C:\DLL\ABC.dll”
AssemblyLoader 类:
public class AssemblyLoader : MarshalByRefObject
{
public void Load(string path)
{
ValidatePath(path);
Assembly.Load(path);
}
public void LoadFrom(string path)
{
ValidatePath(path);
Assembly.LoadFrom(path);
}
public void LoadBytes(string path)
{
ValidatePath(path);
var b = File.ReadAllBytes(path);
Assembly.Load(b);
}
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.Load(assemblyPath);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public Assembly GetAssemblyBytes(string assemblyPath)
{
try
{
var b = File.ReadAllBytes(assemblyPath);
return Assembly.Load(b);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
private void ValidatePath(string path)
{
if (path == null)
throw new ArgumentNullException("path");
if (!File.Exists(path))
throw new ArgumentException(String.Format("path \"{0}\" does not exist", path));
}
}
主类:
static void Main(string[] args)
{
string file1 = @"1\DummyModule.dll";
string file2 = @"2\PSLData.dll";
string file3 = @"3\Security.dll";
try
{
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
var assemblyLoader = (AssemblyLoader)myDomain.CreateInstanceAndUnwrap(typeof(AssemblyLoader).Assembly.FullName, typeof(AssemblyLoader).FullName);
assemblyLoader.LoadBytes(file2);
assemblyLoader.LoadBytes(file3);
var dummy = assemblyLoader.GetAssemblyBytes(file1);
foreach (var t in dummy.GetTypes())
{
var methodInfo = t.GetMethod("D");
if (methodInfo != null)
{
var obj = Activator.CreateInstance(t);
Console.Write(methodInfo.Invoke(obj, new object[] { }).ToString());
}
}
AppDomain.Unload(myDomain);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Console.ReadKey();
}
在上面的代码中,“DummyModule.dll”是主dll,“PSLData.dll”和“Security.dll”是依赖项。
当我调用“DummyModule.dll”的方法“D”时,会出现错误:
Could not load file or assembly 'DummyModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
所有 DLL 文件仍在不同的文件夹中。如何加载所有需要的文件并调用函数?
谢谢。
【问题讨论】:
-
每个做自己的程序集加载的人都应该完成阅读blogs.msdn.microsoft.com/suzcook/tag/loader-info和social.msdn.microsoft.com/search/…的文章...希望最近做过的人能为你提供总结(这真的不会帮助你从长远来看-无论如何考虑阅读文章)
标签: c# .net dll .net-assembly