C# - Referencing a type in a dynamically generated assembly

后端 未结 2 1713
走了就别回头了
走了就别回头了 2020-12-03 08:15

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 e

相关标签:
2条回答
  • 2020-12-03 08:32

    I think that in

    CompilerResults results2 = provider2.CompileAssemblyFromSource(parameters, @"
    namespace Dynamic
    {
        public class B : A
        {
        }
    }
    ");
    

    You want to pass parameters2, not parameters.

    I found the way to do it, you need NOT to compile the first one in memory, if you don't do that, it will create a dll for this assembly in your temp directory, plus, in your call to

    ReferencedAssemblies.Add() 
    

    you dont pass the assembly name, you pass the assembly path, take a look at this code, it should work flawlessly :

            CodeDomProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();            
    
            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.Location);
            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;
            }
    
    0 讨论(0)
  • 2020-12-03 08:39

    MSDN says you can:

    Restrictions on Type References

    Assemblies can reference types defined in another assembly. A transient dynamic assembly can safely reference types defined in another transient dynamic assembly, a persistable dynamic assembly, or a static assembly. However, the common language runtime does not allow a persistable dynamic module to reference a type defined in a transient dynamic module. This is because when the persisted dynamic module is loaded after being saved to disk, the runtime cannot resolve the references to types defined in the transient dynamic module.

    0 讨论(0)
提交回复
热议问题