I am trying to find a way to compile assemblies at runtime and load them. The main intention is to store them in a database that is not on disk. So I wrote the code, but I saw an interesting situation. Here is my code:
namespace SumLib
{
public class SumClass
{
public static int Sum(int a, int b)
{
return a + b;
}
}
}
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();
apd.Load(asbyte);
Console.ReadLine();
}
}
The code works fine with the delete line, it is commented out if I uncomment it, the application domain loads the assembly, the method AssemblyLoadEvent()starts, I see number 9 on the console, but when the method is completed it apd.Load()gives an error message: “Could not load file or assembly”. which is quite reasonable.
The question is, how AssemblyLoadEvent()does the method run without an assembly file on disk?
- , , appdomain Load()?