0

我在我的程序中使用简单的 C# 脚本来动态操作一些数据。目前它们被编译并加载到程序的 AppDomain 中,这很简单,但缺点是无法卸载动态程序集。

假设我的可执行文件有一个类来操作主程序中的数据:

namespace MasterExe;

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

动态代码是这样的:

namespace DynScript;

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

有没有办法让我的类 Dummy 对另一个 AppDomain 可见?

编译脚本时,我已将可执行文件添加到引用的程序集中,但出现以下错误:编译错误:找不到元数据文件“C:\Develop\Master.exe”

exe在那里,但它不会加载它。当使用相同的 AppDomain 时,一切都很好......

编辑:这是我用来在 exe 中编译和加载程序集的代码:

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

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;
    }
}
4

0 回答 0