views:

591

answers:

3

Hello everyone,

I am generating an Assembly on the fly using Reflection.Emit and then saving it. It contains one Type and a static Main() method in it.

.NET is kind enough to automatically reference a required assembly. However, in Main(), there is a call to a method from another assembly and it doesn't get referenced in the standard way.

When the assembly is executed, the runtime looks for this assembly and cannot find it, which is a problem.

Reflector can detect this and shows this extra assembly under the "depends" list. How can I retrieve these implicit dependencies using the Reflection API?

Thanks

+3  A: 

Have you tried Assembly.GetReferencedAssemblies? It returns the AssemblyName of the referenced assemblies.

Megacan
A: 

Hm... The Assembly property of System.Type returns the assembly that defines the type, obviously.

If you have absolutely no control/knowledge about the IL in that Main() method, you'd have to parse the IL you just generated and check if all types mentioned are present.

Much more realistic, is to manually ensure all types involved in the emission of call and callvirt are referenced.

SealedSun
+2  A: 

Thanks for the responses guys, I have managed to resolve the problem.

Here's what happens:

AssemblyBuilder builder = ... // generate assembly

builder.GetReferencedAssemblies(); => It will NOT return a reference to the assembly used in the method body even though I have called Save() already - it seems to return only the assemblies loaded in memory already.

Assembly.ReflectionOnlyLoadFrom(filename).GetReferencedAssemblies() => works fine

I was suggesting you call GetReferencedAssemblies from an instance of Assembly representing the assembly for witch you want to know the references (:P). GetReferencedAssemblies returns a set of AssemblyName instances. It only contains the full name of the assembly, wether its loaded or not.
Megacan