2

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.

MrFox
  • 4,852
  • 7
  • 45
  • 81
  • Possible duplicate of [this](https://stackoverflow.com/questions/38106710/is-using-a-static-class-to-facilitate-access-to-appsettings-acceptable). The short version is that to make code more testable the class shouldn't be static. That way we can supply whatever settings we want when writing tests. If we get values from a web.config/app.config there's no way to test without one and there's no way to test with different values. – Scott Hannen Jun 27 '19 at 16:04

1 Answers1

2

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.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121