Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a InMemory compiled assembly into current domain

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

After the compile I can take the CompilerResults and do something like this:-

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

I get the expected output, the CreateInstance has worked.

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

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

The problem is in this code t ends up being null. Now I suspect that although the assembly is compiled it isn't loaded. I can't seem to find away to load this assembly into the domain so that its type names can be resolved.

Can anyone enlighten me?

like image 513
AnthonyWJones Avatar asked Dec 22 '22 16:12

AnthonyWJones


1 Answers

I'm afraid that is explicitly impossible.

The documentation for Type.GetType clearly states:

If the assembly has not been saved to disk when GetType is called, the method returns null. GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

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

like image 128
Fyodor Soikin Avatar answered Dec 26 '22 07:12

Fyodor Soikin