Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetType fails to create type from already loaded assembly

I have program which loads an assembly using Asssembly.LoadFrom method. Some time later I attempt to use Type.GetType to create a type from that assembly (using AssemblyQualifiedName), but the method returns null. If I set it to throw exception, it tells

Could not load file or assembly '...' or one of its dependencies. The system cannot find the file specified.

But I am sure the exact same assembly is already loaded (it shows in the AppDomain.CurrentDomain.GetAssemblies() list).

Anybody has an idea what could be wrong and/or how to solve this issue?

like image 608
Matěj Zábský Avatar asked Oct 24 '10 17:10

Matěj Zábský


2 Answers

In order to understand why this doesn't work, you need to understand the issue of "load contexts". Type.GetType only looks at the "Load" context. The assembly you loaded into memory was in the "LoadFrom" context.

The only way to really get binds in the load context to see assemblies in the load-from context is to use the AssemblyResolve event and write code to return the correct assembly. The AssemblyResolve event fires right before the bind fails and all other assembly lookup did not succeed.

See the following links for more information about load contexts and issues that arise when using LoadFrom.

MSDN - http://msdn.microsoft.com/en-us/library/dd153782.aspx
AssemblyResolve - http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx
Suzanne Cook - Link

like image 107
Josh Avatar answered Oct 04 '22 05:10

Josh


If you can get the assembly using Assembly.LoadFrom then you can get the type by doing:

        Assembly assembly = Assembly.LoadFrom("whatever");
        Type myType = assembly.GetType("typeName")

The assembly.GetType has other overloads which you can find out about here

like image 39
Steve Ellinger Avatar answered Oct 04 '22 06:10

Steve Ellinger