Changing the web.config will cause a refresh of an IIS website, will it also trigger run a static constructor again?

Viewed 208

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.

1 Answers

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.

Related