asp.net - 如果 ASP.NET 应用程序使用许多 DLL,那么保持每个 dll 的配置独立的最佳方法是什么?

标签 asp.net configuration web-config

在为每个 dll 创 build 置后,将生成一个 .dll.config 文件。如果该 dll 是 asp.net 应用程序的一部分,如何为每个 dll 保持此配置独立并且不将它们合并到 web.config ?

例子: 我有一个 GMailSender 类库 (DLL),它通过 GMail 服务器发送电子邮件。您只需要一个 GMailSender 实例,如下所示:

GMailSender gms = new GMailSender();
gms.To = "myfriend@yahoo.com";
gms.Subject = "System.Configuration dilemma";
gms.Body = "Can anyone help me with this question ?";
gms.Send();

考虑GMailSenderGMailSender.dll里面,它的配置文件是GMailSender.dll.config,GMail账户的用户名和密码是里面。

我希望这个 DLL 使用它自己的配置文件(dll 和配置都在同一目录中,即在 ASP.NET 应用程序的 Bin 文件夹中)或旁边桌面应用程序。这样 GMailSender 独立于谁使用他来检索它的配置(当前 AppDomain 谁加载了这个 DLL)。

我想要这个而不需要重建轮子(没有自定义配置类)。我猜它可能与 System.Configuration 但这个命名空间可能是 .NET 中设计最差的!

请不要说出你为什么这样设计......

这是一个基于插件的设计,最终 MEF 现在在 .NET 4.0 中做了一些,但是 Parts< 也有同样的问题 配置。有了 MEF 至少我不需要再争论 基于插件 的设计优势。

最佳答案

您可以使用自定义配置部分 实现您的需要。这MSDN article提供了有关如何实现此类配置部分的一些详细信息和示例。

如果您需要简单的key/value 配置,例如在 appSettings 部分中,那么创建自定义配置部分非常简单。

您需要做的第一件事是在 web.config 中定义您的配置部分:

<configSections>
  <section name="GmailSettings" restartOnExternalChanges="true" type="System.Configuration.NameValueFileSectionHandler" />
</configSections>

现在在 web.config 文件中,您可以声明 GmailSettings 部分并设置要用于该设置的外部配置文件的位置:

<GmailSettings configSource="GmailSettings.config"></GmailSettings>

configSource 指定用于定义 GmailSettings 部分的外部配置文件的名称和位置。请注意定义该部分时使用的 restartOnExternalChanges 属性。如果您希望应用程序在修改 GmailSettings.config 文件时自动重启(就像修改 web.config 文件时一样),请将其设置为 true。

以下是如何实现 GmailSettings.config 文件的示例:

<?xml version="1.0"?>
<GmailSettings>
  <add key="userName" value="blabla"/>
  <add key="password" value="moreBla"/>
</GmailSettings>

您可以使用 ConfigurationManager.GetSection() 方法或通过实现如下所示的帮助类 从 GmailSettings 访问设置:

public class GmailSettings
{
    private static readonly GmailSettings _instance = new GmailSettings();
    private NameValueCollection _settings = ConfigurationManager.GetSection("GmailSettings") as NameValueCollection;

    public static GmailSettings Instance
    {
        get { return _instance; }
    }

    public string this[string key]
    {
        get { return _settings[key]; }
    }
}

现在可以像 GmailSettings.Instance["userName"] 一样访问设置。

希望这对您有所帮助。

关于asp.net - 如果 ASP.NET 应用程序使用许多 DLL,那么保持每个 dll 的配置独立的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4065056/

相关文章:

c# - 设置asp :CustomValidator text from codebehind

asp.net - 对于同一件事,我可以同时拥有 Controller 和 ApiController 吗?

java - 如何在 Jenkins 中为每项工作全局设置 JVM 选项?

c# - 如何访问外部 .config 文件?

c# - DbModel.Context.tt 下缺少 DbModel.Context.cs 文件

c# - 应用程序 [Win32Exception (0x80004005) : The system cannot find the file specified] with model first EF

java - 使用外部配置文件配置log4j日志级别

java - 如何从字符串中提取变量

c# - Web.Config - 特定文件的 StaticContent ClientCache 设置

c# - 如何停止 web.config 继承