如何为.NET应用程序域重新加载程序集?

我们正在加载一个读取配置文件的程序集(DLL)。 我们需要更改配置文件,然后重新加载程序集。 我们看到第二次加载组件后,配置没有变化。 有谁看到这里有什么问题? 我们在配置文件中省略了读取的细节。

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,因此最好的办法是将逻辑加载到单独的AppDomain中,然后当您想要重新加载程序集时,您必须卸载AppDomain然后重新加载它。

请参阅以下2个链接以获得答案:

  • Jon Shemitz的动态插件
  • 使用AppDomain加载和卸载Steve Holstad的动态程序集

我相信这样做的唯一方法是启动一个新的AppDomain并卸载原来的AppDomain。 这就是ASP.NET始终处理对web.config的更改的方式。

如果您只是更改某些部分,可以使用ConfigurationManager.Refresh(“sectionName”)强制从磁盘重新读取。

 static void Main(string[] args) { var data = new Data(); var list = new List(); 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文件。)