I have a static class that loads the value of my connection string every time a connection needs to be made. This is done to ensure the newest connectionstring is used when it's changed. But it's for a website that's hosted in IIS, so the site is restarted any time the web.config is changed anyway.
So the connectionstring could also be loaded statically:
using System.Configuration;
public static class Settings
{
static Settings()
{
Database = ConfigurationManager.ConnectionStrings["database"].ConnectionString;
Timeout = ConfigurationManager.AppSettings["timeout"];
}
public static string Database { get; }
public static string Timeout { get; }
}
Would this allow changing the database connection for an IIS site after deployment?
And for a Windows Service?
Edit: Apparently the question was poorly formulated. I know how to ensure the configured value is reloaded, the question is whether this specific setup will do the job. It's a yes/no question.
I'm aware of how to make it so the property is read every time. My concern is for performance. Doing a file read every time is expensive. I'd rather just access a static property. Considering that a save of the web.config will restart the website and thus a file read anyway; my code doesn't also need to do this. So the more specific question is:
Will saving the the web.config trigger my static constructor, therefore re-loading the configuration value?
Another edit: changed the question at the top as well.
Starting with C# 6.0 you can use expression bodied readonly properties , so your class can be written like this:
using System.Configuration;
public static class Settings
{
public static string Database => ConfigurationManager.ConnectionStrings["database"].ConnectionString;
public static string Timeout => ConfigurationManager.AppSettings["timeout"];
}
Expression bodied properties will execute the expression each time they are accessed, so if a change happened in the configuration file you don't even need to restart the service.
Further reading: This SO post and the one it's linked to .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.