关于C#中动态加载AppDomain的问题
2009-06-24 07:08:14 来源:WEB开发网一旦Assembly被作业管理器的服务器调用,(比如某个执行计划正好要被执行了),在调用之前会将程序集加载到默认AppDomain,然后执行,这就有个问题,如果我需要做替换或者删除Assembly等这些操作的时候,由于Assembly已经被默认AppDomain加载,那么对它的更改肯定是不允许的,它会弹出这样的错误:
除非你关掉作业管理服务器,然后再操作,显然这样做是很不合理的。
并且默认AppDomain是不能被卸载的,那么我们该怎么办呢,我想到的方法是动态的加载Assembly,新建一个AppDomain,让Assembly加载到这个新AppDomain中然后执行,当执行完后卸载这个新的AppDomain即可,方法如下:
1、创建程序集加载类AssemblyDynamicLoader,该类用来创建新的AppDomain,并生成用来执行.Net程序的RemoteLoader类:
using System;
using System.Collections.Generic;
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);
}
}
}
更多精彩
赞助商链接