相关疑难解决方法(0)

How to load an assembly from byte array into a non-default AppDomain without accessing the app directory?

I have an in-memory assembly MyAssembly (class library) that is used in my main assembly MyApp.exe:

byte[] assemblyData = GetAssemblyDataFromSomewhere();
Run Code Online (Sandbox Code Playgroud)

(For testing, the GetAssemblyDataFromSomewhere method can just do File.ReadAllBytes for an existing assembly file, but in my real app there is no file.)

MyAssembly has only .NET Framework references and has no dependencies to any other user code.

I can load this assembly into the current (default) AppDomain:

Assembly.Load(assemblyData);

// this works
var obj = Activator.CreateInstance("MyAssembly", "MyNamespace.MyType").Unwrap();
Run Code Online (Sandbox Code Playgroud)

Now, …

.net c# appdomain assembly-loading .net-assembly

7
推荐指数
1
解决办法
454
查看次数

DisallowApplicationBaseProbing = true时需要连接AssemblyResolve事件

设置DisallowApplicationBaseProbing = true时,我需要在创建的AppDomain上连接AssemblyResolve事件。我这样做的原因是强制运行时调用需要解析程序集的AssemblyResolve事件,而不是先进行探测。这样,另一个开发人员就不能仅将MyDllName.dll粘贴在ApplicationBase目录中,并覆盖我想在AssemblyResolve事件中加载的程序集。

这样做的问题如下:

  class Program
  {
 static void Main()
 {
    AppDomainSetup ads = new AppDomainSetup();
    ads.DisallowApplicationBaseProbing = true;
    AppDomain appDomain = AppDomain.CreateDomain("SomeDomain", null, ads);
    appDomain.AssemblyResolve += OnAssemblyResolve;
    appDomain.DoCallBack(target);
 }

 static System.Reflection.Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
 {
    Console.WriteLine("Hello");
    return null;

 }

 private static void target()
 {
    Console.WriteLine(AppDomain.CurrentDomain);
 }
  }
Run Code Online (Sandbox Code Playgroud)

代码永远不会超出+ = OnAssemblyResolve行。

当代码尝试执行时,新的应用程序域将尝试解析我正在其中执行的程序集。由于DisallowApplicationBaseProbing = true,因此不知道在哪里可以找到该程序集。看来我有鸡肉和鸡蛋问题。它需要解析我的程序集以连接程序集解析器,但需要程序集解析器来解析我的程序集。

感谢您提供的所有帮助。

-麦克风

c# assembly-resolution

4
推荐指数
1
解决办法
1998
查看次数