天天看点

揭开.NET 2.0配置之谜(三)

let's go on!

在我研究和实验配置节的时候,我学到一些技巧,可是使他们更容易使用。自定义配置节的某些方面非常乏味,如所有时间一直通过调用<code>ConfigurationManager.GetSection("someSectionName")获取SomeSectionClass。为了减轻繁琐乏味,我尝试在我的<code>ConfigurationSection</code>类中使用下列方式:</code>

public class SomeConfigurationSection  

{  

    static SomeConfigurationSection()  

    {  

        // Preparation...  

    }  

    // Properties...  

    #region GetSection Pattern  

    private static SomeConfigurationSection m_section;  

    /// &lt;summary&gt;  

    /// Gets the configuration section using the default element name.  

    /// &lt;/summary&gt;  

    public static SomeConfigurationSection GetSection()  

        return GetSection("someConfiguration");  

    /// Gets the configuration section using the specified element name.  

    public static SomeConfigurationSection GetSection(string definedName)  

        if (m_section == null)  

        {         

            m_section = ConfigurationManager.GetSection(definedName) as   

                        SomeConfigurationSection;  

            if (m_section == null)  

                throw new ConfigurationException("The &lt;" + definedName +   

                      "&gt; section is not defined in your .config file!");  

        }      

        return m_section;  

    #endregion  

上述的模式增加了一个静态<code>GetSection()</code>方法给每个自定义<code>ConfigurationSection</code>类。它的一个重载方法,以一个字符串作为参数,允许你为.config中元素定义一个不同的名字,如果你喜欢的话。另外,默认的重载是可以使用的。这种模式使用在标准的应用程序(.exe)的配置节下工作的非常好。然而,如果配置节使用在一个web.config文件中,你将需要使用下面的代码:

using System.Web;  

using System.Web.Configuration;  

    /// &lt;remarks&gt;  

    /// If an HttpContext exists, uses the WebConfigurationManager  

    /// to get the configuration section from web.config.  

    /// &lt;/remarks&gt;  

        {  

            string cfgFileName = ".config";  

            if (HttpContext.Current == null)  

            {  

                m_section = ConfigurationManager.GetSection(definedName)   

                            as SomeConfigurationSection;  

            }  

            else 

                m_section = WebConfigurationManager.GetSection(definedName)   

                cfgFileName = "web.config";  

                  "&gt; section is not defined in your " +   

                  cfgFileName + " file!");  

正如你看到的,在ASP.NET下访问配置节需要使用<code>System.Web.Configuration.WebConfigurationManager</code>,而不是<code>System.Configuration.ConfigurationManager</code>。检查当前的<code>HttpContext</code>足以确定使用哪个管理器(manager)去获取配置节。还有一个增强,我们对这种模式,使得允许我们可以保存修改。我们知道,必须使用<code>Configuration</code>对象来保存修改,因为管理器(manager)类不提供<code>Save()</code>方法。我们可以在我们的GetSection方法中创建一个<code>Configuration</code>对象,但是最终将缺乏灵活性、效率不高。在最终完全的模式中,我这样做,把<code>Configuration</code>对象作为一个参数:

    // Dictionary to store cached instances of the configuration object  

    private static Dictionary&lt;string,   

            SomeConfigurationSection&gt; m_sections;  

    /// Finds a cached section with the specified defined name.  

    private static SomeConfigurationSection   

            FindCachedSection(string definedName)  

        if (m_sections == null)  

            m_sections = new Dictionary&lt;string,   

                             SomeConfigurationSection&gt;();  

            return null;  

        }  

        SomeConfigurationSection section;  

        if (m_sections.TryGetValue(definedName, out section))  

            return section;  

        return null;  

    /// Adds the specified section to the cache under the defined name.  

    private static void AddCachedSection(string definedName,   

                   SomeConfigurationSection section)  

        if (m_sections != null)  

            m_sections.Add(definedName, section);  

    /// Removes a cached section with the specified defined name.  

    public static void RemoveCachedSection(string definedName)  

        m_sections.Remove(definedName);  

    /// to get the configuration section from web.config. This method  

    /// will cache the instance of this configuration section under the  

    /// specified defined name.  

        if (String.IsNullOrEmpty(definedName))  

            definedName = "someConfiguration";  

        SomeConfigurationSection section = FindCachedSection(definedName);  

        if (section == null)  

                section = ConfigurationManager.GetSection(definedName)   

                          as SomeConfigurationSection;  

                section = WebConfigurationManager.GetSection(definedName)   

            if (section == null)  

                   "&gt; section is not defined in your " + cfgFileName +   

                   " file!");  

            AddCachedSection(definedName, section);  

        return section;  

    /// Gets the configuration section using the default element name   

    /// from the specified Configuration object.  

    public static SomeConfigurationSection GetSection(Configuration config)  

        return GetSection(config, "someConfiguration");  

    /// Gets the configuration section using the specified element name   

    public static SomeConfigurationSection GetSection(Configuration config,   

                                           string definedName)  

        if (config == null)  

            throw new ArgumentNullException("config",   

                  "The Configuration object can not be null.");  

        SomeConfigurationSection section = config.GetSection(definedName)   

                                           as SomeConfigurationSection;  

            throw new ConfigurationException("The &lt;" + definedName +   

                  "&gt; section is not defined in your .config file!");  

通过传递<code>Configuration</code>对象,一个可保存的配置节实例能在XML文件中检索一个指定名字的配置节。这把我带到另外一个重要的配置节秘诀。配置节元素的名字不一定必须的固定不变,也不一定只有一个配置节的实例。在一个.config文件按中每个配置节可以定义和设置多次,只要给每个实例不同的名字:

&lt;configuration&gt; 

  &lt;configSections&gt; 

    &lt;section name="example1" type="Examples.Configuration.ExampleSection,  

                                      Examples.Configuration" /&gt; 

    &lt;section name="example2" type="Examples.Configuration.ExampleSection,   

    &lt;section name="example3" type="Examples.Configuration.ExampleSection,   

  &lt;/configSections&gt; 

  &lt;example1 /&gt; 

  &lt;example2 /&gt; 

  &lt;example3 /&gt; 

&lt;/configuration&gt; 

以同样的方式配置节组也可以定义多次。这使得一个通常的自定义配置结构在同一个应用程序中,同时以多种方式使用,而且使得自定义配置可以重用。因为可能在一个.config文件中一个配置节定义多次,最终实现上述的模式包括一个简单的实例缓存。每次用不同的<code>definedName</code>调用<code>GetSection(string)</code>,将返回不同的配置节对象且存储在缓存中。连续以相同的名字调用将返回相同的缓存实例。这种模式的另一个重要方面是缺少为两个新版本的<code>GetSection</code>(以一个<code>Configuration</code>对象作为参数的<code>GetSection</code>方法)的缓存。用<code>Configuration</code>对象比用<code>ConfigurationManager</code>或WebConfigurationManager花费更大的开销。通过配置管理器(manager)调用<code>GetSection()</code>方法将完全缓存节,而通过<code>Configuration</code>对象调用将导致节每次都要被解析。一般来说,<code>Configuration</code>对象只有当需要保存配置更改是才使用。配置管理器类应该被用来访问读取配置。这将保证使用配置设置时性能最佳。

最后一个秘诀是关于性能的主题。除非你实现高级的配置节或元素,包括事件通知,缓存配置设置在变量中通常沮丧的(行不通的)。更多关于这个的讨论将在下面的高级部分,首先考虑以下非常简单的情景:

public class SomeProgram  

    static Main()  

        s_config = MyConfig.GetSection();  

        s_duration = s_config.Duration;  

        s_timer = new Timer(  

            new TimerCallback(),  

            null,  

            TimeSpan.Zero  

            s_duration  

        );  

        Console.ReadKey();  

        s_timer.Dispose();  

    private static MyConfig s_config;  

    private static Timer s_timer;  

    private static TimeSpan s_duration;  

    private static void WriteCurrentTime(object data)  

        Console.WriteLine("The current time is " + DateTime.Now.ToString());  

        if (s_duration != s_config.Duration)  

            s_duration = s_config.Duration;  

            s_timer.Change(TimeSpan.Zero, s_duration);  

在上面的应用程序中,我们希望如果配置文件更新的话,改变定时器间隔。我们配置节的实例,s_config,将一直保持更新。因此如果在应用程序运行时,.config文件改变,任何改变将被发现并载入到内存中。如果你跟我在文章中一样实现你的配置节,覆写静态构造器和替换属性(properties)集合,这样你的集合将有有高的性能。这使得访问一个配置属性(property)相对廉价的操作,因此上述代码可以重写成如下:

            s_config.Duration  

        Console.WriteLine("The current time is " +   

                          DateTime.Now.ToString());         

        s_timer.Change(TimeSpan.Zero, s_config.Duration);  

如果这个例子过于简单揭示直接使用配置设置的意义,那么想象一个更复杂的场景,一个配置值在一个缓存变量。变量是顺序通过一个链来调用,然后循环使用。如果想要的结果对任何配置的过期及时发现并回答,那么缓存将不起作用。你必须直接访问配置属性(property),不用把它缓存到变量中。配置设置是全局访问的,可以在应用程序的任何地方。这意味着在你的代码中的任何地方都可以访问配置属性(property),而不用缓存变量的值和传递一个变量参数。将使得代码更干净,因为你要求更少的的参数。如果高性能是绝对必要的,是有可能写一个有事件的配置节,当配置数据在磁盘上已经改变能通知使用者。然而,这是一个更高级的主题,将在以后讨论。

本文中概述的信息提供了一个全面地介绍.NET 2.0框架的配置功能特性。然而,这决不是一个全面的文件,并且还有一些更复杂的使用配置节。其他信息将在后面的文章:

解码.NET 2.0配置之谜

破解.NET 2.0配置之谜

12.1、附录A: 配置结构的级联

在ASP.NET应用程序中,web.config文件可能针对任何IIS“应用程序”。倘若应用程序的虚拟文件夹是另一个应用程序的孩子,来自父应用程序的web.config文件将和子应用程序的web.config合并。因为IIS中的应用程序可以嵌套任何级别的深度,当子应用应程序的web.config加载时,配置级联将产生。

假设我们有一个站点安装在IIS里,以下面的层次结构且每个web.config文件包含一个共同的集合:

\wwwroot  

      web.config  

      \firstapp  

          web.config  

      \anotherapp  

          \childapp  

              web.config  

      \finalapp  

&lt;!-- \wwwroot\web.config --&gt; 

    &lt;commonCollection&gt; 

        &lt;add key="first"  value="C98E4F32123A" /&gt; 

        &lt;add key="second" value="DD0275C8EA1B" /&gt; 

        &lt;add key="third"  value="629B59A001FC" /&gt; 

    &lt;/commonCollection&gt; 

&lt;!-- \wwroot\firstapp\web.config --&gt; 

        &lt;remove key="first" /&gt;          

        &lt;add key="first"  value="FB54CD34AA92" /&gt; 

        &lt;add key="fourth" value="DE67F90ACC3C" /&gt; 

&lt;!-- \wwroot\anotherapp\web.config --&gt; 

        &lt;add key="fourth" value="123ABC456DEF" /&gt; 

        &lt;add key="fifth"  value="ABC123DEF456" /&gt; 

        &lt;add key="sixth"  value="0F9E8D7C6B5A" /&gt; 

&lt;!-- \wwroot\anotherapp\childapp\web.config --&gt; 

        &lt;remove key="second" /&gt; 

        &lt;remove key="fourth" /&gt; 

        &lt;remove key="sixth" /&gt; 

        &lt;add key="seventh" value="ABC123DEF456" /&gt; 

        &lt;add key="ninth"  value="0F9E8D7C6B5A" /&gt; 

&lt;!-- \wwroot\lastapp\web.config --&gt; 

        &lt;clear /&gt; 

        &lt;add key="first"  value="AABBCCDDEEFF" /&gt; 

        &lt;add key="second" value="112233445566" /&gt; 

        &lt;add key="third"  value="778899000000" /&gt; 

        &lt;add key="fourth" value="0A0B0C0D0E0F" /&gt; 

如果我们研究了每个应用程序的集合,结果将如下:

\wwwroot\web.config

first = C98E4F32123A

second = DD0275C8EA1B

third = 629B59A001FC

\wwwroot\firstapp\web.config

first = FB54CD34AA92

fourth = DE67F90ACC3C

\wwwroot\anotherapp\web.config

fourth = 123ABC456DEF

fifth = ABC123DEF456

sixth = 0F9E8D7C6B5A

\wwwroot\anotherapp\childapp\web.config

seventh = ABC123DEF456

ninth = 0F9E8D7C6B5A

\wwwroot\lastapp\web.config

first = AABBCCDDEEFF

second = 112233445566

third = 778899000000

fourth = 0A0B0C0D0E0F

我希望这个简单的示例,子应用程序的web.config是如何继承设置的,这些设置是如何被覆写,足够了。你可能不是经常遇到这种情况,但是了解发生了什么,以及如何覆写父web.config的配置设置,应该有助于减轻ASP.NET开发者的配置文件问题。

12.2、附录B: 包含外部配置文件

尽管在.NET 2.0的配置功能中都很伟大,但是仍有一个缺点。当工作在一个多环境的单一项目中,管理配置文件是一个噩梦。管理多环境下的多版本的配置文件(如开发、测试、阶段、产品)的过程,我目前的工作包括手工比较.config文件,将更改部署到一个环境或另外一个,通过手工合并。我花了几个月试图找到一种更好的方法,最终找到了。进入这样那样一些没有“没有文档的”或很少文档的——微软著名的特点,的其中的一个:configSource。当我用Reflector深入挖掘.NET 2.0配置源码的时候,碰到这个珍品,美妙的小工具。

每个配置节在被.NET配置类解析和加载时,都分配了一个<code>SectionInformation</code>对象。<code>SectionInformation</code>对象包含关于配置节的元信息,并允许管理节如何互相覆写,当定义在一个子web.config中时(ASP.NET)。现在,我们将忽略大部分<code>SectionInformation</code>对象提供的,考虑configSource属性(property)。通过添加configSource属性(attribute)到任何<code>ConfigurationSection的</code>根元素,你可以指定一个备用,外部的配置设置将被加载。

&lt;configuration&gt;  

  &lt;connectionStrings configSource="externalConfig/connectionStrings.config"/&gt;  

&lt;/configuration&gt;  

&lt;!-- externalConfig/connectionStrings.config --&gt;  

&lt;connectionStrings&gt;  

  &lt;add name="conn" connectionString="blahblah" /&gt;  

&lt;/connectionStrings&gt; 

在上面的配置文件中,<code>&lt;connectionStrings&gt;</code>节源于名为externalConfig/connectionStrings.config的文件。所有应用程序的连接字符串将加载自这个特定文件。现在,连接字符串是从外部资源加载的,在相对相同位置的每个环境,他相对简单地创建一个connectionStrings.config文件。因此externalConfig/   connectionStrings.config 文件的路径。这里漂亮的地方是,我们可以正确地为每个环境定义连接字符串定义一次。我们不用担心意外覆写那些设置,在部署一个config文件时,无论是否合并得当或根本不合并。这是一个巨大的福音,当更改一个应用程序到产品环境是,他的关键正确的数据库连接字符串存在。使用configSource属性(attribute)失效,就是它要求所有的配置节将放置在外部文件中。没有继承或覆写是可能的,在某些情况下使它没用。所有的外部配置文件用configSource属性(attribute)引用,也必须放在相对子到主的.config文件路径上。我相信这是考虑web环境中的安全性,存储文件在相对父路径上。

别的需要注意的是<code>&lt;appSettings&gt;</code>节有一个更好的选择使用configSource,称为<code>file</code>。如果你使用<code>file</code>属性(attribute)而不是configSource在<code>&lt;appSettings&gt;</code>节里,你可以定义设置在根.config文件或引用文件都可以。根.config文件的设置也能被引用文件覆写,简单地用相同的键添加东西。可悲的是,<code>file</code>属性(attribute)只适用在<code>&lt;appSettings&gt;</code>节,而不是建立在配置框架下。在我们自己的配置节中也可能实现类似的属性(attribute)。这将在将来的高级配置主题部分讨论,几个先决部分之后。

请继续关注!

     本文转自Saylor87 51CTO博客,原文链接:http://blog.51cto.com/skynet/365552,如需转载请自行联系原作者