我在程序中使用简单的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;
}
}