我正在尝试找到一种在运行时编译程序集并加载它们的方法。基本意图是将它们存储在数据库中而不是磁盘上。因此,我编写了一些代码,但看到了一个有趣的情况。这是我的代码:
//SumLib
namespace SumLib
{
public class SumClass
{
public static int Sum(int a, int b)
{
return a + b;
}
}
}
// Console app
class Program
{
public static void AssemblyLoadEvent(object sender, AssemblyLoadEventArgs args)
{
object[] tt = { 3, 6 };
Type typ = args.LoadedAssembly.GetType("SumLib.SumClass");
MethodInfo minfo = typ.GetMethod("Sum");
int x = (int)minfo.Invoke(null, tt);
Console.WriteLine(x);
}
static void Main(string[] args)
{
AppDomain apd = AppDomain.CreateDomain("newdomain", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);
apd.AssemblyLoad += new AssemblyLoadEventHandler(AssemblyLoadEvent);
FileStream fs = new FileStream("Sumlib.dll", FileMode.Open);
byte[] asbyte = new byte[fs.Length];
fs.Read(asbyte, 0, asbyte.Length);
fs.Close();
fs.Dispose();
// File.Delete("Sumlib.dll");
apd.Load(asbyte);
Console.ReadLine();
}
}
当删除行已注释时,代码可以完美运行。如果取消注释,则应用程序域将加载程序集,
AssemblyLoadEvent()
方法运行,控制台上出现数字9,但是当方法结束时,apd.Load()
抛出一个错误:"无法加载文件或程序集",这很合理。
问题是:没有磁盘上的程序集文件,如何让 AssemblyLoadEvent()
方法运行?
如果该方法以某种方式通过原始二进制数据运行,则是否有任何方法使 appdomain 成功完成 Load()
方法?