Use AppDomain to load/unload external assemblies

后端 未结 8 2058
遇见更好的自我
遇见更好的自我 2020-12-24 08:39

My scenario is as follows:

  • Create new AppDomain
  • Load some assemblies into it
  • Do some magic with loaded dlls
  • Unload AppDomain to rele
8条回答
  •  青春惊慌失措
    2020-12-24 09:14

    Actually, combination of above answers pointed me to (I hope) correct answer: My code is now as follows:

    AppDomain newDomain = AppDomain.CreateDomain("newDomain", e, setup);
    string fullName = Assembly.GetExecutingAssembly().FullName;
    Type loaderType = typeof(AssemblyLoader);
    FileStream fs = new FileStream(@"library.dll", FileMode.Open);
    byte[] buffer = new byte[(int)fs.Length];
    fs.Read(buffer, 0, buffer.Length);
    fs.Close();
    
    Assembly domainLoaded = newDomain.Load(buffer);
    object loaded = Activator.CreateInstance(domainLoaded.GetTypes()[1]);
    AppDomain.Unload(newDomain);
    GC.Collect();
    GC.WaitForPendingFinalizers();
    

    I can't use AppDomain.CreateInstance, since it requires Assembly.FullName which I don't know - library is loaded dynamically.

    Thanks for the help, Bolek.

提交回复
热议问题