开发者

Thoughts on how to refer to web.config key names in code

开发者 https://www.devze.com 2023-01-06 05:34 出处:网络
When your web.config or app.config file has an appsettings entry, what is the best way t开发者_运维问答o refer to its key in your code file?

When your web.config or app.config file has an appsettings entry, what is the best way t开发者_运维问答o refer to its key in your code file?

Developers I have worked with have differing opinions on this. Some say to hard code the string and others suggest that there should be a file containing string constants and in your code, you use the constant as the appsettings key.

I would be interested in hearing other opinions on this. What do you do? Why is it the best?


String constants are better than nothing, but I'd initially vote for using a configuration class to provide strongly typed, intellisense friendly access to the config values. If I were stuck with using AppSettings for some reason.

In a more perfect world, I would vote for avoiding appSettings altogether and using custom configuration classes as they are much, much cleaner in the long run.


Skip the string constants, and create a configuration wrapper class instead.

class MyConfiguration
{
    public static string SomeConfigValue
    {
        get
        {
            return WebConfigurationManager.AppSettings["SomeConfigValue"];
        }
    }

    public static int SomeOtherConfigValue
    {
        get
        {
            return int.Parse(WebConfigurationManager.AppSettings["SomeOtherConfigValue"];
        }
    }

    //..and so on
}

Then you could get it like this:

string s = MyConfiguration.SomeConfigValue;
int i = MyConfiguration.SomeOtherConfigValue;

(You might consider not going the static route if you want to remove dependencies on the configuration system while unittesting)


String Constants for the win.

Keeping common strings in string constants makes things easier to maintain. If a key in your config file changes names, you only have to change it in one spot rather than worrying about finding every instance of the hard-coded string throughout your application.


I've always been a fan of Rick Strahl's method.

As for static strings being unwieldy, break your class down into subclasses and properties if you need to. For example in an application I'm currently working on, I have App.Settings for general settings, App.EmailSettings for email settings, and App.EventSettings for event logging settings.

0

精彩评论

暂无评论...
验证码 换一张
取 消