Upload the assembled InMemory assembly to the current domain

I use CSharpCodeProvider to compile the assembly, and I have the CompileParameters GenerateInMemory property set to true because I don't want to create a physical file.

After compiling, I can take CompilerResults and do something like this: -

  object x = cr.CompiledAssembly.CreateInstance("MyGeneratedClass"); Console.WriteLine(x); 

I get the expected result, CreateInstance worked.

However, I need to have access to types in the current AppDomain without such assembly knowledge. I need to do something like this: -

  Type t = Type.GetType("MyGeneratedClass"); object x = Activator.CreateInstance(t); 

The problem in this code t ends with zero. Now I suspect that although the assembly is compiled, it is not loaded. I can't seem to find this assembly in the domain so that its type names can be resolved.

Can someone enlighten me?

+4
source share
2 answers

I am afraid that this is clearly impossible.

The documentation for Type.GetType clearly states:

If the assembly was not saved to disk when calling GetType, the method returns null. GetType does not understand transitional dynamic assemblies; therefore, calling GetType to retrieve the type in the transient dynamic assembly returns null.

You will need to write the assembly to disk if you want it to behave just like any regular assembly.

+6
source

The GenerateInMemory property is a trick in the living room. The C # compiler does not know how to write to the memory of your program. This is a fake, the compiler asked to actually write the assembly to the TEMP directory. Where does it load into memory after compilation completed successfully with FileStream in byte [], then Assembly.Load (byte []). Take a look at the Reflector tool, Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch ().

Since it creates a file in any case, it’s just not very noticeable, solve your problem by simply creating the file and uploading it to AppDomain.

+5
source

Source: https://habr.com/ru/post/1343361/


All Articles