接下来在原来基础上需要修改的是
·将编译成的DLL保存到磁盘中
·创建另外的AppDomain
·获得IRemoteInterface接口的引用(将生成的DLL加载到额外的AppDomain)
·调用InvokeMethod方法来远程调用
·可以通过AppDomainUnload()方法卸载程序集
以下是完整的代码演示了如何应用这一方案
//get the code to compile
string strSourceCode = thistxtSourceText;
// Create an addtional AppDomain
AppDomainSetup objSetup = new AppDomainSetup();
objSetupApplicationBase = AppDomainCurrentDomainBaseDirectory;
AppDomain objAppDomain = AppDomainCreateDomain(MyAppDomain null objSetup);
// Create a new CSharpCodePrivoder instance
CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
// Sets the runtime compiling parameters by crating a new CompilerParameters instance
CompilerParameters objCompilerParameters = new CompilerParameters();
objCompilerParametersReferencedAssembliesAdd(Systemdll);
objCompilerParametersReferencedAssembliesAdd(SystemWindowsFormsdll);
// Load the remote loader interface
objCompilerParametersReferencedAssembliesAdd(RemoteAccessdll);
// Load the resulting assembly into memory
objCompilerParametersGenerateInMemory = false;
objCompilerParametersOutputAssembly = DynamicalCodedll;
// CompilerResults: Complile the code snippet by calling a method from the provider
CompilerResults cr = objCSharpCodePrivoderCompileAssemblyFromSource(objCompilerParameters strSourceCode);
if (crErrorsHasErrors)
{
string strErrorMsg = crErrorsCountToString() + Errors:;
for (int x = ; x < crErrorsCount; x++)
{
strErrorMsg = strErrorMsg + \r\nLine: +
crErrors[x]LineToString() + +
crErrors[x]ErrorText;
}
thistxtResultText = strErrorMsg;
MessageBoxShow(There were build erros please modify your code Compiling Error);
return;
}
// Invoke the method by using Reflection
RemoteLoaderFactory factory = (RemoteLoaderFactory)objAppDomainCreateInstance(RemoteAccessRemoteAccessRemoteLoaderFactory)Unwrap();
// with help of factory create a real LiveClass instance
object objObject = factoryCreate(DynamicalCodedll DynamiclyHelloWorld null);
if (objObject == null)
{
thistxtResultText = Error: + Couldnt load class;
return;
}
// *** Cast object to remote interface avoid loading type info
IRemoteInterface objRemote = (IRemoteInterface)objObject;
object[] objCodeParms = new object[];
objCodeParms[] = Allan;
string strResult = (string)objRemoteInvoke(GetTime objCodeParms);
thistxtResultText = strResult;
//Dispose the objects and unload the generated DLLs
objRemote = null;
AppDomainUnload(objAppDomain);
SystemIOFileDelete(DynamicalCodedll);
[] [] [] [] []