I have a method which compiles a 'module', a 'module' contains a string of valid C# read from a .cs file. I am wondering whether it's possible to pass an object from the class that contains the method to compile the module, to the assembly that is created allowing for the code initially in the .cs file to use that object.
Here is the code I use to compile the modules
public void CompileModule(string strModuleName)
{
CompilerParameters objCompilerParameters = new CompilerParameters();
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = true;
objCompilerParameters.IncludeDebugInformation = false;
CodeDomProvider objCompiler = CSharpCodeProvider.CreateProvider("CSharp");
CompilerResults objCompilerResults = objCompiler.CompileAssemblyFromSource(objCompilerParameters, Modules[strModuleName].Source);
if (objCompilerResults.Errors.HasErrors)
{
throw new InvalidOperationException("Syntax error.");
}
Assembly objCompiledAssembly = objCompilerResults.CompiledAssembly;
MethodInfo objMethod = objCompiledAssembly.GetType(Modules[strModuleName].ClassName).GetMethod(Modules[strModuleName].CallMethod);
Console.WriteLine((string)objMethod.Invoke(null, null));
}
Modules is just a dictionary of dictionary<string,>, Module being the name of the class that contains the contents of the .cs file.
If the module source is
public static class Echo
{
public static string strTest = "Testing";
public static string EchoTestString()
{
return strTest;
}
}
How would I be able to pass an instantiated object (of type Fruit) to the assembly, so I could use the Fruit object however I wanted inside of the Echo class? So the .cs file could essentially just be
public static class Echo
{
public static string EchoFruitName()
{
return Fruit.Name;
}
}
Fruit being defined in my compiler class and passed across to the compiled Echo class of course.
Any ideas?
Thanks in advance. :)