How can I get ASP.NET to reload on file changes?
I have an ASP.NET application that is part of a much larger system; it reads most of its configuration from files above the root level of the web application.
Since the application has already been written and the configuration file format has been chosen to facilitate editing by clients, I cannot use the solution in "Shared Configuration Files in .NET".
I hope ASP.NET has an API that I can call during startup to tell it which file to view. (I could write this the hard way using "FileSystemWatcher" and catch events and then restart myself, however it would be a shame, since ASP.NET already has code to watch files and reload when they change.)
Also, which ASP.NET API am I calling to force ASP.NET to restart in a good way?
Here are some links I found that might help: Using FileSystemWatcher from ASP.NET and Extending FileSystemWatcher to ASP.NET
In one case, I cached the configuration in the ASP.NET cache and set the CacheDependency. In another case requiring faster access, I used a FileSystemWatcher and updated the static field when the configuration changed.
(I never really learned how to restart ASP.NET from code in a sane way.)
a source to share
static FileSystemWatcher ConfigWatcher;
static void StartWatchConfig() {
ConfigWatcher = new FileSystemWatcher("configPath") {
Filter = "configFile"
};
ConfigWatcher.Changed += new FileSystemEventHandler(ConfigWatcher_Changed);
ConfigWatcher.EnableRaisingEvents = true;
}
static void ConfigWatcher_Changed(object sender, FileSystemEventArgs e) {
HttpRuntime.UnloadAppDomain();
}
a source to share
If you know that your application will never access the configuration outside of the HttpContext, consider caching your configuration and add a CacheDependency to the file.If the file changes, your cached configuration is removed and you can re-add it with updated values.
Sort of:
public MyConfigObj GetConfig()
{
var config = Cache["configkey"] as MyConfigObj;
if(config == null)
{
var configPath = Server.MapPath("myconfigpath");
config = GetConfigFromFile(configPath);
Cache.Insert("configkey", config, new CacheDependency(configPath));
}
return config;
}
a source to share
For the second part, you can use the following code snippet to run the AppPool utility (which is the same as restarting IIS, only at the application level, not the entire server).
using System.DirectoryServices;
public void RecycleAppPool(string machine, string appPoolName)
{
string path = "IIS://" + machine + "/W3SVC/AppPools/" + appPoolName;
DirectoryEntry w3svc = new DirectoryEntry(path);
w3svc.Invoke("Recycle", null);
}
(from here )
a source to share
I think you will need to create a service that uses FileSystemWatcher to monitor changes to configuration files outside of the web application directory - and then when a change is detected, make a minor change to the web.config file in the web application and save it to restart the application.
a source to share