Exception when receiving a link to a Link from another AppDomain

I load all the DLLs from a specific "extensions" directory into the new AppDomain to get some reflection related information.

Here is what I am trying:

I created a new AssemblyProxy library in my solution that just has this class:

 public class AssemblyProxy : MarshalByRefObject { public Assembly LoadFile( string assemblyPath ) { try { return Assembly.LoadFile( assemblyPath ); } catch { return null; } } } 

I make sure that this DLL is present in my "extensions" directory. Then I use the following code to load all the assemblies from the extensions directory into the new AppDomain .

 foreach( string extensionFile in Directory.GetFiles( ExtensionsDirectory, "*.dll" ) ) { Type type = typeof( AssemblyProxy.AssemblyProxy ); var value = (AssemblyProxy.AssemblyProxy) Domain.CreateInstanceAndUnwrap( type.Assembly.FullName, type.FullName ); var extensionAssembly = value.LoadFile( extensionFile ); types.AddRange( extensionAssembly.GetTypes() ); } 

Some DLLs load successfully, but in some DLLs an exception is thrown as follows:

Could not load file or assembly 'Drivers, Version=2.3.0.77, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

EDIT: The exception is not added to the new AppDomain. DLL successfully loaded into the new AppDomain. An exception is received as soon as the assembly reference is returned to the main / calling AppDomain. Is the main / calling AppDomain an attempt to download the assembly by myself just by getting the link?

Thanks.

+6
source share
1 answer

You should not return the Assembly object from the new AppDomain , because it will only work if the main AppDomain has access to those assemblies that it does not, because the assemblies are in a directory that:

One way to avoid this is to follow leppie's and comments:

  • Create a serialized type that includes the minimum information you need from the Assembly object.
  • Add this type to the new assembly accessed by AppDomain. The easiest way to do this is by adding it to the GAC.

Another approach would be to use Mono.Cecil instead of System.Reflection . Mono.Cecil allows you to validate assemblies without downloading them. For a very simple example, look at the second half of the answer.

+2
source

All Articles