0

I am using simple C# scripts in my program to manipulate some data dynamically. Currently they are compiled and loaded to program's AppDomain which is nice for simplicity but downside is that there is no way to unload dynamic assemblies.

Lets say my executable has a class to manipulate data in main program:

namespace MasterExe;

public class Dummy()
{
   public void SetValue(int val) { }
}

And dynamic code is this:

namespace DynScript;

public class DynClass
{
    public void SomeDynamicCode(MasterExe.Dummy cl)
    {
       cl.SetValue(1);
    }
}

Is there way to get my class Dummy visible to another AppDomain?

I have added my executable to referenced assemblies when compiling script but I am getting following error: Compile error: Metadata file 'C:\Develop\Master.exe' could not be found

The exe is there but it wont load it. When using same AppDomain all good...

EDIT: Here is code I am using to compile and load assemblies in the exe:

var SandBox = AppDomain.CreateDomain("ScriptSandbox");
var ScriptEngine = (DynamicScript)Sandbox.CreateInstanceFromAndUnwrap("DynamicAssembly.dll", "DynamicAssembly.DynamicScript");
var assembly = ScriptEngine.Compile(sourcecode);

And actual code in DynamicAssembly.dll:

public Assembly Compile(string sourceCode)
{
    Dictionary<string, string> ProviderOptions = new Dictionary<string, string>();
    ProviderOptions.Add("CompilerVersion", "v3.5");

    CompilerParameters cp = new CompilerParameters();
    cp.GenerateInMemory = true;
    cp.IncludeDebugInformation = false;
    cp.TempFiles = new TempFileCollection();
    cp.CompilerOptions = "/target:library /optimize";
    cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

    using (var compiler = new CSharpCodeProvider(ProviderOptions))
    {
        return compiler.CompileAssemblyFromSource(cp, sourceCode).CompiledAssembly;
    }
}
itix
  • 59
  • 11
  • could you share the code you use to compile? – Bruno Belmondo Dec 22 '17 at 13:39
  • Would be good if you add some code (how you create dynamic assembly, how you load it into another app domain and so on). Preferrably in a way that we can just copy and paste. – Evk Dec 22 '17 at 13:39
  • I added the code I am using to compile. Actual compilation is done in separate DLL. – itix Dec 22 '17 at 14:05
  • Error is: The type or namespace name 'MasterExe.Exe' could not be found (are you missing a using directive or an assembly reference?) – itix Dec 22 '17 at 14:08
  • Am I missing something here? From the question, I didn't get why you would want to dynamically compile at all? i.e. manipulate some data? – zc246 Dec 22 '17 at 14:11
  • This is used in I/O module to have programmable logic. I didn't want to introduce my own scripting language so I am (ab)using C# compiler. – itix Dec 22 '17 at 14:25

0 Answers0