Say I have a string of code as below that I compile in my main project. But I want to implement an interface in the CustomClass. The interface is located in another project in my solution (part of the references in my main project) When I do this
public class CustomClass : InterfaceType
I get an error like this. How can I reference the other project so that I canmake use of the interface and other classes that are part of it, within my dynamic code?
c:\Users\xxx\AppData\Local\Temp\m8ed4ow-.0.cs(1,32: error CS0246: The type or namespace name 'InterfaceType' could not be found (are you missing a using directive or an assembly reference?)
string code2 =
" public class CustomClass : InterfaceType " +
" {" +
" }";
// Compiler and CompilerParameters
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters compParameters = new CompilerParameters();
compParameters.GenerateInMemory = false; //default
//compParameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);
compParameters.IncludeDebugInformation = true;
//compParameters.TempFiles.KeepFiles = true;
compParameters.ReferencedAssemblies.Add("System.dll");
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
// Compile the code
CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code2);
// Check the compiler results for errors
StringWriter sw = new StringWriter();
foreach (CompilerError ce in res.Errors)
{
if (ce.IsWarning) continue;
sw.WriteLine("{0}({1},{2}: error {3}: {4}", ce.FileName, ce.Line, ce.Column, ce.ErrorNumber, ce.ErrorText);
}
string error = sw.ToString();
sw.Close();
// Create a new instance of the class 'CustomClass'
object myClass = res.CompiledAssembly.CreateInstance("CustomClass");
The bottom line is that you need to add the other project to your CompilerParameters.ReferencedAssemblies collection. This can be tricky, because CodeDOM needs to be able to get to the assembly and thus the assembly either needs to be in the GAC or you need to add a full path to the assembly to the ReferencedAssemblies location.
One easy way to do this, if you are referencing the project that contains "InterfaceType" in the project that is executing the CodeDOM compiler, is to do something like this: compilerParameters.ReferencedAssemblies.Add(typeof(InterfaceType).Assembly.Location);. If not, you'll have to figure out some other method for making sure CodeDOM can find the assembly you want to reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With