我需要加载DLL和依赖项。在我的数据库中,我已经保存了所有依赖项(引用文件的路径)。
即:
要加载的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文件仍在不同的文件夹中。如何加载所有需要的文件并调用函数?
感谢。
答案 0 :(得分:0)
尝试使用它..它对我有用..
serviceAgentAssembly =System.Reflection.Assembly.LoadFrom(string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", assemblyPath, assemblyName));
foreach (Type objType in serviceAgentAssembly.GetTypes())
{
//further loops to get the method
//your code to ivoke the function
}
答案 1 :(得分:0)
你正在使用程序集的相对路径,所以问题是“相对于什么?”您创建并加载程序集的新AppDomain在树林中丢失;它不会继承您在其中创建它的AppDomain的相同探测路径。查看类 System.AppDomainSetup 及其属性 ApplicationBase 和 PrivateBinPath 以及采用实例的CreateDomain()形式AppDomainSetup作为参数。最简单的解决方案是使用由 AppDomain.CurrentDomain.SetupInformation 返回的AppDomainSetup实例,当前域当然是创建新域的应用程序。