C# 如何为.NET应用程序域重新加载程序集?
我们正在加载一个读取配置文件的程序集(DLL)。我们需要更改配置文件,然后重新加载程序集。我们看到,在第二次加载程序集后,配置没有变化。 有人看到这里出了什么问题吗?我们在配置文件中遗漏了读取的细节C# 如何为.NET应用程序域重新加载程序集?,c#,.net,appdomain,C#,.net,Appdomain,我们正在加载一个读取配置文件的程序集(DLL)。我们需要更改配置文件,然后重新加载程序集。我们看到,在第二次加载程序集后,配置没有变化。 有人看到这里出了什么问题吗?我们在配置文件中遗漏了读取的细节 AppDomain subDomain; string assemblyName = "mycli"; string DomainName = "subdomain"; Type myType; Object myObject; // Load Application domain + Asse
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。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();
}
static void Main(字符串[]args)
{
var data=新数据();
var list=新列表();
list.Add(newparent().Set(data));
var configValue=ConfigurationManager.AppSettings[“TestKey”];
Console.WriteLine(配置值);
WriteLine(“更新配置文件…”);
Console.ReadKey();
configValue=ConfigurationManager.AppSettings[“TestKey”];
WriteLine(“刷新前:{0}”,configValue);
ConfigurationManager.RefreshSection(“应用设置”);
configValue=ConfigurationManager.AppSettings[“TestKey”];
WriteLine(“刷新后:{0}”,configValue);
Console.ReadKey();
}
(请注意,如果您正在使用VS主机进程进行测试,则必须更改application.vshost.exe.config文件。)请参阅以下2个链接以获取答案: