强类型调用 web.config 而不重复属性名称?

发布于 2024-07-23 08:53:26 字数 541 浏览 2 评论 0原文

我在这里寻找答案。 如果之前有人问过这个问题,我很抱歉(我怀疑已经问过)。

摘要:如何在不重复属性名称的情况下对 web.config 进行强类型调用?


详细信息:在我的代码中,我尝试尽量减少字符串的使用,并且我不喜欢重复定义某些内容。

对这两种习惯的补充是我将 AppSettings 使用(及其字符串)限制为一个类,我在整个项目中引用了该类。 AppSettings 类公开公共属性:

    12   public static string DateFormatString {
    13       get {
    14           return ConfigurationManager.AppSettings["DateFormatString"];
    15       }
    16   }

如何保留此类并防止属性名称重复(第 12 行和第 14 行)?

或者,您可以推荐什么其他解决方案?

I searched here for the answer. I'm sorry if this has been asked before (as I suspect it has).

Summary: How can I have strongly typed calls into my web.config without duplicating the property names?


Details: In my code, I try to minimize string usage, and I don't like defining something twice.

Complementing both of these wonts is my restriction of AppSettings usage (and its strings) to one class, which I reference throughout the project. The AppSettings class exposes public properties:

    12   public static string DateFormatString {
    13       get {
    14           return ConfigurationManager.AppSettings["DateFormatString"];
    15       }
    16   }

How can I keep this class and prevent the duplication (lines 12 & 14) of the property name?

Alternatively, what other solution might you recommend?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

怀中猫帐中妖 2024-07-30 08:53:26

您的示例中没有重复:一个 DateFormatString 是属性名称,另一个是字符串。 您只是遵循一个约定,将属性命名为与值的查找键相同的名称。

我确实看到了一个可能的改进。 您应该在静态构造函数中读取一次配置文件并存储值,而不是每次访问属性时都从 AppSettings 中读取它们。

There's no duplication in your example: One DateFormatString is a property name and the other is a string. You're just following a convention which names the property identically to the lookup key for the value.

I do see one possible improvement. You should read the config file once in a static constructor and store the values instead of reading them from AppSettings every time a property is accessed.

南街九尾狐 2024-07-30 08:53:26

我可能建议将 web.config 反序列化为一个对象。 然后,您可以访问所有配置条目,就好像它们是属性一样(没有比这更强类型的了!)

I'd probably recommend deserializing the web.config into an object. You can then access all configuration entries as if they were properties (can't get much more strongly typed than that!)

坚持沉默 2024-07-30 08:53:26

我为不直接属于我的所有内容创建一个包装器。 这包括缓存、会话、配置、外部 Web 服务等。这使我能够封装使用该小部件的脏细节。 在配置方面,我有一个简单的配置类,它公开了我保存的 app.config 或 web.config 的各种属性。 这可能看起来像这样:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using RanchBuddy.Core.Services.Impl;
using StructureMap;

namespace RanchBuddy.Core.Services.Impl
{
    [Pluggable("Default")]
    public class ConfigurationService : IConfigurationService
    {
        internal static int GetDefaultCacheDuration_Days()
        {
            return Convert.ToInt32(ConfigurationManager.AppSettings["DefaultCacheDuration_Days"]);
        }

        ...

        internal static LoggingType GetLoggingType()
        {
            string loggingType = ConfigurationManager.AppSettings["LoggingType"].ToString();
            if(loggingType.ToLower() == "verbose")
            {
                return LoggingType.Verbose;
            }
            else if (loggingType.ToLower() == "error")
            {
                return LoggingType.Error;
            }
            return LoggingType.Error;
        }

        ...

        public static string GetRoot()
        {
            string result = "";
            if(ConfigurationManager.AppSettings["Root"] != null)
            {
                result = ConfigurationManager.AppSettings["Root"].ToString();
            }
            return result;
        }
    }
}

在这里,您可以做的不仅仅是从配置文件中获取值。 您可以将字符串转换为它需要的类型。 您可以使用该字符串来确定要返回的枚举值。 等等。但关键是任何需要对配置进行的更改都可以在此处进行。 如果您想更换配置存储的机制,请包括在内!

I create a wrapper for everything that doesn't belong to me directly. This includes cache, session, configuration, external web services, etc. This allows me to encapsulate the dirty details of using that widget. In the case of configuration I have a bare bones configuration class that exposes the various properties that I have housed my app.config or web.config. This might look something like this:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using RanchBuddy.Core.Services.Impl;
using StructureMap;

namespace RanchBuddy.Core.Services.Impl
{
    [Pluggable("Default")]
    public class ConfigurationService : IConfigurationService
    {
        internal static int GetDefaultCacheDuration_Days()
        {
            return Convert.ToInt32(ConfigurationManager.AppSettings["DefaultCacheDuration_Days"]);
        }

        ...

        internal static LoggingType GetLoggingType()
        {
            string loggingType = ConfigurationManager.AppSettings["LoggingType"].ToString();
            if(loggingType.ToLower() == "verbose")
            {
                return LoggingType.Verbose;
            }
            else if (loggingType.ToLower() == "error")
            {
                return LoggingType.Error;
            }
            return LoggingType.Error;
        }

        ...

        public static string GetRoot()
        {
            string result = "";
            if(ConfigurationManager.AppSettings["Root"] != null)
            {
                result = ConfigurationManager.AppSettings["Root"].ToString();
            }
            return result;
        }
    }
}

Inside here you can do more than simply get values from the config file. You can convert a string to the type that it needs to be. You can use the string to determine an enum value to be returned. Etc. But the key is that any changes that ever need to be made regarding configuration can be made here. To include if you want to swap out the mechanism for the configuration store!

沐歌 2024-07-30 08:53:26

使用配置部分设计器构建您自己的ConfigurationSection,这样您就不会根本必须使用 AppSettings...但您将拥有自己的设置集合,甚至在 web.config 文件中包含 Intellisense。

Build your own ConfigurationSection with the Configuration Section Designer, this way you don't have to use AppSettings at all... but you'll have your own collection of settings that will even have Intellisense in the web.config file.

好听的两个字的网名 2024-07-30 08:53:26

一种解决方案可能是,

public enum Settings
{
    None,
    DateFormatString,
    DefeaultUserPrefix,
    SomeOtherValue
}

然后有一个辅助类,例如,

public static class ConfigurationHelper
{
     public static Get<T>(Settings setting)
     {
         string output = ConfigurationManager.AppSettings[setting.ToString()];
         if(string.isNullOrEmpty(output))
               throw new ConfigurationErrorsException("Setting " + setting + " is not defined in Configuration file.");
         return (T)output; //You can probably use Convert.* functions. 
     }
}

您的调用代码将如下所示,

ConfigurationHelper.Get<string>(Settings.DateFormatString);

上述方法提供了某种程度的强类型,但您仍然必须确保配置文件中的设置名称与枚举的名称匹配。

最好的选择是根据配置文件自动生成类。


如果您想要强类型属性,您可以编写

public static string DateFormatString
{
    get { return ConfigurationHelper.Get<string>(Settings.DateFormatString); }
}

另外,我建议不要在构造函数中读取配置文件(过早优化?)。 如果您在构造函数中读取配置文件,则意味着您无法在应用程序运行时更改配置文件。

One solution could be,

public enum Settings
{
    None,
    DateFormatString,
    DefeaultUserPrefix,
    SomeOtherValue
}

and then have a helper class like,

public static class ConfigurationHelper
{
     public static Get<T>(Settings setting)
     {
         string output = ConfigurationManager.AppSettings[setting.ToString()];
         if(string.isNullOrEmpty(output))
               throw new ConfigurationErrorsException("Setting " + setting + " is not defined in Configuration file.");
         return (T)output; //You can probably use Convert.* functions. 
     }
}

Your calling code will look like,

ConfigurationHelper.Get<string>(Settings.DateFormatString);

The above approach provides some level of strong typing but you still have to make sure that the settings name in config file matches with the name of the enum.

The best choice would be to auto-generate class based on the configuration file.


If you wanted strongly typed properties, you can write

public static string DateFormatString
{
    get { return ConfigurationHelper.Get<string>(Settings.DateFormatString); }
}

Also, I would advice against reading the config file in constructor (premature optimization?). If you read the config file in constructor, it means that you can not change config file while application is running.

半边脸i 2024-07-30 08:53:26

我编写了一个 nuget 包 来执行此操作(除其他外)。 附带的博客文章介绍了详细信息,但这个简化的代码片段显示了相关的要点对于你的问题。

public string DateFormatString =>
    ConfigurationManager.AppSettings[MethodBase.GetCurrentMethod().Name.Replace("get_", "")];

I have written a nuget package that does this (among other things). The accompanying blog post goes in to the details, but this simplified snippet shows the gist of it as related to your question.

public string DateFormatString =>
    ConfigurationManager.AppSettings[MethodBase.GetCurrentMethod().Name.Replace("get_", "")];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文