關於C#中動態載入AppDomain的問題
在作業系統中,利用程式可以對正在執行的應用程式進行隔離,每個應用程式被載入到單獨的程式中,併為其分配虛擬記憶體,程式無法直接訪問實體記憶體,只能通過作業系統將虛擬記憶體對映到實體記憶體中,並保證程式之間的實體記憶體不會重疊,但是程式最大的缺點就是效率問題,尤其是程式的切換開銷很大,而程式間不能共享記憶體,所以不可能從一個程式通過傳遞指標給另一個程式。
在.NET中出現了一個新的概念:AppDomain——應用程式域,所有.NET應用程式都需要執行在託管環境中,作業系統能提供的只有程式,因此.NET程式需要通過AppDomain這個媒介來執行在程式中,同時使用該incheng提供的記憶體空間,只要是.NET的應用都會執行在某個AppDomain中。
當我們執行一個.NET應用程式或者執行庫宿主時,OS會首先建立一個程式,然後會在程式中載入CLR(這個載入一般是通過呼叫_CorExeMain或者_CorBindToRuntimeEx方法來實現),在載入CLR時會建立一個預設的AppDomain,它是CLR的執行單元,程式的Main方法就是在這裡執行,這個預設的AppDomain是唯一且不能被解除安裝的,當該程式消滅時,預設AppDomain才會隨之消失。
一個程式中可以有多個AppDomain,且它們直接是相互隔離的,我們的Assembly是不能單獨執行的,它必須被載入到某個AppDomain中,要想解除安裝一個Assembly就只能解除安裝其AppDomain。
最近在我所參加的一個專案中要實現這樣一個模組:定製一個作業管理器,它可以定時的以不同頻率執行某些.Net應用程式或者儲存過程,這裡的頻率可以是僅一次、每天、每週還是每月進行執行計劃的實施,對於呼叫儲存過程沒什麼好說的,但是呼叫.Net應用程式的時候就需要考慮如下問題:
一旦Assembly被作業管理器的伺服器呼叫,(比如某個執行計劃正好要被執行了),在呼叫之前會將程式集載入到預設AppDomain,然後執行,這就有個問題,如果我需要做替換或者刪除Assembly等這些操作的時候,由於Assembly已經被預設AppDomain載入,那麼對它的更改肯定是不允許的,它會彈出這樣的錯誤: ,除非你關掉作業管理伺服器,然後再操作,顯然這樣做是很不合理的。
並且預設AppDomain是不能被解除安裝的,那麼我們該怎麼辦呢,我想到的方法是動態的載入Assembly,新建一個AppDomain,讓Assembly載入到這個新AppDomain中然後執行,當執行完後解除安裝這個新的AppDomain即可,方法如下:
1、建立程式集載入類AssemblyDynamicLoader,該類用來建立新的AppDomain,並生成用來執行.Net程式的RemoteLoader類:
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using Ark.Log;
/// <summary>
/// The local loader.
/// </summary>
public class AssemblyDynamicLoader
{
/// <summary>
/// The log util.
/// </summary>
private static ILog log = LogManager.GetLogger(typeof(AssemblyDynamicLoader));
/// <summary>
/// The new appdomain.
/// </summary>
private AppDomain appDomain;
/// <summary>
/// The remote loader.
/// </summary>
private RemoteLoader remoteLoader;
/// <summary>
/// Initializes a new instance of the <see cref="LocalLoader"/> class.
/// </summary>
public AssemblyDynamicLoader()
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationName = "ApplicationLoader";
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
setup.PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "private");
setup.CachePath = setup.ApplicationBase;
setup.ShadowCopyFiles = "true";
setup.ShadowCopyDirectories = setup.ApplicationBase;
this.appDomain = AppDomain.CreateDomain("ApplicationLoaderDomain", null, setup);
String name = Assembly.GetExecutingAssembly().GetName().FullName;
this.remoteLoader = (RemoteLoader)this.appDomain.CreateInstanceAndUnwrap(name, typeof(RemoteLoader).FullName);
}
/// <summary>
/// Invokes the method.
/// </summary>
/// <param name="fullName">The full name.</param>
/// <param name="className">Name of the class.</param>
/// <param name="argsInput">The args input.</param>
/// <param name="programName">Name of the program.</param>
/// <returns>The output of excuting.</returns>
public String InvokeMethod(String fullName, String className, String argsInput, String programName)
{
this.remoteLoader.InvokeMethod(fullName, className, argsInput, programName);
return this.remoteLoader.Output;
}
/// <summary>
/// Unloads this instance.
/// </summary>
public void Unload()
{
try
{
AppDomain.Unload(this.appDomain);
this.appDomain = null;
}
catch (CannotUnloadAppDomainException ex)
{
log.Error("To unload assembly error!", ex);
}
}
}
2、建立RemoteLoader類,它可以在AppDomain中自由穿越,這就需要繼承System.MarshalByRefObject這個抽象類,這裡RemoteLoader如果不繼承MarshalByRefObject類則一定會報錯(在不同AppDomain間傳遞物件,該物件必須是可序列化的)。以RemoteLoader類做為代理來呼叫待執行的.Net程式。
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
/// <summary>
/// The Remote loader.
/// </summary>
public class RemoteLoader : MarshalByRefObject
{
/// <summary>
/// The assembly we need.
/// </summary>
private Assembly assembly = null;
/// <summary>
/// The output.
/// </summary>
private String output = String.Empty;
/// <summary>
/// Gets the output.
/// </summary>
/// <value>The output.</value>
public String Output
{
get
{
return this.output;
}
}
/// <summary>
/// Invokes the method.
/// </summary>
/// <param name="fullName">The full name.</param>
/// <param name="className">Name of the class.</param>
/// <param name="argsInput">The args input.</param>
/// <param name="programName">Name of the program.</param>
public void InvokeMethod(String fullName, String className, String argsInput, String programName)
{
this.assembly = null;
this.output = String.Empty;
try
{
this.assembly = Assembly.LoadFrom(fullName);
Type pgmType = null;
if (this.assembly != null)
{
pgmType = this.assembly.GetType(className, true, true);
}
else
{
pgmType = Type.GetType(className, true, true);
}
Object[] args = RunJob.GetArgs(argsInput);
BindingFlags defaultBinding = BindingFlags.DeclaredOnly | BindingFlags.Public
| BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase
| BindingFlags.InvokeMethod | BindingFlags.Static;
CultureInfo cultureInfo = new CultureInfo("es-ES", false);
try
{
MethodInfo methisInfo = RunJob.GetItsMethodInfo(pgmType, defaultBinding, programName);
if (methisInfo == null)
{
this.output = "EMethod does not exist!";
}
if (methisInfo.IsStatic)
{
if (methisInfo.GetParameters().Length == 0)
{
if (methisInfo.ReturnType == typeof(void))
{
pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
this.output = "STo call a method without return value successful.";
}
else
{
this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
}
}
else
{
if (methisInfo.ReturnType == typeof(void))
{
pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
this.output = "STo call a method without return value successful.";
}
else
{
this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
}
}
}
else
{
if (methisInfo.GetParameters().Length == 0)
{
object pgmClass = Activator.CreateInstance(pgmType);
if (methisInfo.ReturnType == typeof(void))
{
pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, null, cultureInfo);
this.output = "STo call a method without return value successful.";
}
else
{
this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, null, cultureInfo); //'ymtpgm' is program's name and the return value of it must be started with 'O'.
}
}
else
{
object pgmClass = Activator.CreateInstance(pgmType);
if (methisInfo.ReturnType == typeof(void))
{
pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, args, cultureInfo);
this.output = "STo call a method without return value successful.";
}
else
{
this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, args, cultureInfo); //'ymtpgm' is program's name and the return value of it must be started with 'O'.
}
}
}
}
catch
{
this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
}
}
catch (Exception e)
{
this.output = "E" + e.Message;
}
}
}
其中的InvokeMethod方法只要提供Assembly的全名、類的全名、待執行方法的輸入引數和其全名就可以執行該方法,該方法可以是帶引數或不帶引數,靜態的或者不是靜態的。
最後這樣使用這兩個類:
String output = loader.InvokeMethod("fileName", "ymtcla", "yjoinp", "ymtpgm");
loader.Unload();