如何重新加载.NET应用程序域的程序集?
问题描述:
我们加载组件(一个DLL)读取一个配置文件。我们需要更改配置文件,然后重新加载程序集。我们发现第二次加载程序集后,配置没有任何变化。 有人看到这里有什么问题吗?我们在配置文件中省略了阅读的细节。如何重新加载.NET应用程序域的程序集?
AppDomain subDomain;
string assemblyName = "mycli";
string DomainName = "subdomain";
Type myType;
Object myObject;
// Load Application domain + Assembly
subDomain = AppDomain.CreateDomain(DomainName,
null,
AppDomain.CurrentDomain.BaseDirectory,
"",
false);
myType = myAssembly.GetType(assemblyName + ".mycli");
myObject = myAssembly.CreateInstance(assemblyName + ".mycli", false, BindingFlags.CreateInstance, null, Params, null, null);
// Invoke Assembly
object[] Params = new object[1];
Params[0] = value;
myType.InvokeMember("myMethod", BindingFlags.InvokeMethod, null, myObject, Params);
// unload Application Domain
AppDomain.Unload(subDomain);
// Modify configuration file: when the assembly loads, this configuration file is read in
// ReLoad Application domain + Assembly
// we should now see the changes made in the configuration file mentioned above
答
我认为要做到这一点的唯一方法是开始一个新的AppDomain和卸载原来的一个。这就是ASP.NET一直处理对web.config的更改的方式。
答
一旦它被载入您不能卸载的组件。但是,您可以卸载AppDomain,因此最好的办法是将逻辑加载到单独的AppDomain中,然后当您要重新加载程序集时,您必须卸载AppDomain,然后重新加载它。
答
如果你只是改变某些部分,您可以使用ConfigurationManager.Refresh(“sectionName”)强制从磁盘中读取重。
static void Main(string[] args)
{
var data = new Data();
var list = new List<Parent>();
list.Add(new Parent().Set(data));
var configValue = ConfigurationManager.AppSettings["TestKey"];
Console.WriteLine(configValue);
Console.WriteLine("Update the config file ...");
Console.ReadKey();
configValue = ConfigurationManager.AppSettings["TestKey"];
Console.WriteLine("Before refresh: {0}", configValue);
ConfigurationManager.RefreshSection("appSettings");
configValue = ConfigurationManager.AppSettings["TestKey"];
Console.WriteLine("After refresh: {0}", configValue);
Console.ReadKey();
}
(请注意,你必须改变,如果你使用的是VS宿主进程,测试这个时候application.vshost.exe.config文件。)
为什么你的东东d在更新配置文件后重新加载组件?它是否包含动态创建的类型定义? – 2009-06-21 14:52:05
米奇 - 是的他们做 – 2009-06-23 07:49:48