技术开发 频道

揭开.NET 2.0配置隐藏的秘密

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

using System.Web;
using System.Web.Configuration;

public class SomeConfigurationSection
{
    
static SomeConfigurationSection()
    {
        
// Preparation...
    }
    
    
// Properties...
    
    #region GetSection Pattern
    
private static SomeConfigurationSection m_section;
    
    
/// <summary>
    /// Gets the configuration section using the default element name.
    /// </summary>
    /// <remarks>
    /// If an HttpContext exists, uses the WebConfigurationManager
    /// to get the configuration section from web.config.
    /// </remarks>
    public static SomeConfigurationSection GetSection()
    {
        
return GetSection("someConfiguration");
    }
    
    
/// <summary>
    /// Gets the configuration section using the specified element name.
    /// </summary>
    /// <remarks>
    /// If an HttpContext exists, uses the WebConfigurationManager
    /// to get the configuration section from web.config.
    /// </remarks>
    public static SomeConfigurationSection GetSection(string definedName)
    {
        
if (m_section == null)
        {
            string cfgFileName
= ".config";
            
if (HttpContext.Current == null)
            {
                m_section
= ConfigurationManager.GetSection(definedName)
                            as SomeConfigurationSection;
            }
            
else
            {
                m_section
= WebConfigurationManager.GetSection(definedName)
                            as SomeConfigurationSection;
                cfgFileName
= "web.config";
            }
                
            
if (m_section == null)
                
throw new ConfigurationException("The <" + definedName +
                  
"> section is not defined in your " +
                  cfgFileName
+ " file!");
        }    
        
        
return m_section;
    }
    #endregion
}
0
相关文章