I'm trying to figure out if it's possible when you are dynamically generating assemblies, to reference a type in a previously dynamically generated assembly.
For example:
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
CodeDomProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results = provider.CompileAssemblyFromSource(parameters, @"
namespace Dynamic
{
public class A
{
}
}
");
Assembly assem = results.CompiledAssembly;
CodeDomProvider provider2 = new CSharpCodeProvider();
CompilerParameters parameters2 = new CompilerParameters();
parameters2.ReferencedAssemblies.Add(assem.FullName);
parameters2.GenerateInMemory = true;
CompilerResults results2 = provider2.CompileAssemblyFromSource(parameters2, @"
namespace Dynamic
{
public class B : A
{
}
}
");
if (results2.Errors.HasErrors)
{
foreach (CompilerError error in results2.Errors)
{
Console.WriteLine(error.ErrorText);
}
}
else
{
Assembly assem2 = results2.CompiledAssembly;
}
This code prints the following on the console: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
I've tried it lots of different ways, but nothing seems to be working. Am I missing something? Is this even possible?
EDIT: Fixing the bug in the code provides this error instead:
Metadata file 'l0livsmn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' could not be found
EDIT2: Bit of a side note, but changing GenerateInMemory to false, and doing parameters2.ReferencedAssemblies.Add(assem.Location);
will cause it to compile correctly, but I'd greatly prefer to reference the assembly that is directly in memory rather than outputting temporary files.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…