none
appdomain 动态加载卸载dll时的问题 RRS feed

  • 问题

  •        

    代码如下,

    当执行到 下面这句时提示错误:未能加载文件或程序集“test1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项。系统找不到指定的文件。

    其中test1.dll,test2.dll都放在 APP\dllsDir\

    测试过,test1.dll不引用test2.dll,也出现如上错误。

    谢谢!!!

    Assembly ass = ad.Load(buffer);

    static void Main(string[] args) { //要动态加载的dll string dll = AppDomain.CurrentDomain.BaseDirectory + "\\dllsDir\\test1.dll"; AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationName = "setup" + Guid.NewGuid().ToString().Replace("-", ""); setup.ApplicationBase = System.Environment.CurrentDirectory; setup.PrivateBinPath =“dllsDir”; setup.DisallowBindingRedirects = false; setup.DisallowCodeDownload = true; setup.CachePath = setup.ApplicationBase; setup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; //创建一个新域 AppDomain ad = AppDomain.CreateDomain(setup.ApplicationName, AppDomain.CurrentDomain.Evidence, setup); FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\dllsDir\\test1.dll", FileMode.Open); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); //当运行到这里时提示: /* 未能加载文件或程序集“test1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项。系统找不到指定的文件。 */ Assembly ass = ad.Load(buffer); Type type = ass.GetType("test1.Class1"); object instance = ass.CreateInstance("test1.Class1"); MethodInfo mi = type.GetMethod("set"); //执行DLL方法 value = mi.Invoke(instance, new object[] { "123456" }); AppDomain.Unload(ad); Console.WriteLine(value.ToString()); Console.ReadKey(); } //test1.dll namespace test1 { [Serializable] public class Class1 : test2.IClass1 { public string set(string name) { return "test1.Class1." + name; } } }

    //test2.dll

    namespace test2
    {
        public interface IClass1
        {
            string set(string name);
        }
    }



    dog

    2018年4月8日 5:56

全部回复

  • 需要hook一下AssemblyResolve事件

    https://docs.microsoft.com/en-us/dotnet/framework/app-domains/resolve-assembly-loads

    using System; using System.Reflection; class BadExample { static void Main() { AppDomain ad = AppDomain.CreateDomain("Test"); ad.AssemblyResolve += MyHandler; try { object obj = ad.CreateInstanceAndUnwrap( "MyAssembly, version=1.2.3.4, culture=neutral, publicKeyToken=null", "MyType"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } static Assembly MyHandler(object source, ResolveEventArgs e) { Console.WriteLine("Resolving {0}", e.Name); return Assembly.Load(e.Name); } }

    MyHandler方法中将Assembly.Load改为LoadFrom(),参数为test1.dll所在路径和程序集名称。


    专注于.NET ERP/CRM开发框架,C/S架构,SQL Server + ORM(LLBL Gen Pro) + Infragistics WinForms

    2018年4月9日 0:50