C# - Referencing a type in a dynamically generated assembly

Posted by Ashley on Stack Overflow See other posts from Stack Overflow or by Ashley
Published on 2010-05-13T20:40:31Z Indexed on 2010/05/13 20:44 UTC
Read the original article Hit count: 255

Filed under:
|
|
|

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(parameters, @"
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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about dynamic