title: C# Loading assemblies dynamically
body: <p>I'm having an issue when compiling text into dynamic objects at runtime. </p>
  
  <p>I wrote a simple piece of code to compile the text:</p>
  
  <pre><code>public class CompileFactory
  {
      public dynamic Compile(String classCode, String mainClass, Object[] requiredAssemblies)
      {
          CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary&lt;string, string&gt; 
            { 
               { "CompilerVersion", "v4.0" } 
            });
  
          CompilerParameters parameters = new CompilerParameters
          {
              GenerateExecutable = true,       // Create a dll
              GenerateInMemory = true,          // Create it in memory
              WarningLevel = 3,                 // Default warning level
              CompilerOptions = "/optimize",    // Optimize code
              TreatWarningsAsErrors = false     // Better be false to avoid break in warnings
          };
  
          // Add all extra assemblies required
          foreach (var extraAsm in requiredAssemblies)
          {
              parameters.ReferencedAssemblies.Add(extraAsm as string);
          }
          CompilerResults results = provider.CompileAssemblyFromSource(parameters, classCode);
          if (results.Errors.Count != 0)
          {
              return "FAILED";
          }
          return results.CompiledAssembly.CreateInstance(mainClass); ;
      }
  }
  </code></pre>
  
  <p>This is how I am using the <code>Compile</code> method.</p>
  
  <pre><code>List&lt;string&gt; assemblies = new List&lt;string&gt;{"System.Net.Mail.dll", "System.Net.dll"};
  dynamic obj = compile.Compile(fileText, pluginName, assemblies.ToArray()); 
  </code></pre>
  
  <p>As you can see I'm adding references to extra assemblies at some point. For some reason when I add <code>using System.Net;</code> to the text file, it will not be referenced and I get errors. The text I'm compiling is literally a .cs file saved as text. I thought of working around this by extracting the <code>using *</code> and adding them separately, however for when adding <code>System.Net.Mail.dll</code>, the metadata file cannot be found.</p>
  
  <p>Has anyone experienced something similar? I really would like to just add the <code>using *</code> to the file and be ready with it.
  Any input would be greatly appreciated.</p>