.NET配置文件解析过程详解
在我看来,WEB project的开发与WINFORM的开发最大的区别在于web的运行是在Framework上更高一层框架上运行,即ASP。NET框架,程序员在web下的开发可以说是黑盒开发,不是让你去定义程序入口和执行顺序,而是asp.net来调用你的各个方法,程序员做的一切都是一种受控的舞蹈。就像我们调用nunit之类的工具来测试一个dll一样,nunit是容器,是框架,执行哪个方法是由nunt来决定的。因此,也就有了页面执行周期各状态等令刚入门的程序员困惑不已的事,其实,究其根源,在于不了解容器而去使用容器。对于asp.net框架的学习,我们不妨从配置文件开始。
对于程序开发者而言,写配置文件是经常性的工作,如果你写了一个xx.config文件,如果没有详尽的注释,别人恐怕很难读懂,没有良好的配置架构,程序也失去了活力。在我看来,.net配置文件的特点在于反射定义和继承性。
我们访问配置文件时经常觉得配置文件的结构不太符合我们的需要,我们需要从里面更方便地获得自己定义的对象,而不仅仅是key和value,对于自定义配置文件的著述已有很多,在此不再描述,有兴趣的朋友可以访问http://ly4cn.cnblogs.com/archive/2005/09/06/231245.html。
自定义配置节其实还是在.net配置文件架构的应用而已,我们先来搞懂配置文件的结构,弄清楚.net配置文件的运行方式。下面是machine.config的一部分内容:
<configSections>
<section name="runtime" type="System.Configuration.IgnoreSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowLocation="false" />
<sectionGroup name="system.net">
<section name="authenticationModules" type="System.Net.Configuration.NetAuthenticationModuleHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
sectionGroup>
configSections>
SDK中的定义为:
<section
name="section name"
type="configuration section handler class, assembly"
allowDefinition="Everywhere|MachineOnly|MachineToApplication"
allowLocation="true|false" />
的定义为:
<sectionGroup
name="section group name"/>
sectionGroup>
我们来看看.net框架内是如何利用这种结构的。反编译System.dll找到GetConfig方法,在里面我们发现实际获取config的工作默认是由实现了IConfigurationSystem的DefaultConfiguationSystem类来实现的。
public static object GetConfig(string sectionName)


{
if (!ConfigurationSettings._configurationInitialized)

{
lock (typeof(ConfigurationSettings))

{
if ((ConfigurationSettings._configSystem == null) && !ConfigurationSettings.SetConfigurationSystemInProgress)

{
ConfigurationSettings.SetConfigurationSystem(new DefaultConfigurationSystem());
}
}
}
if (ConfigurationSettings._initError != null)

{
throw ConfigurationSettings._initError;
}
return ConfigurationSettings._configSystem.GetConfig(sectionName);
}
我们再来看DefaultConfigurationSystem,这个类主要包含了machine.config的名称路径的基本信息和一些uri操作,而实际的GetConfig的操作交给了ConfiguationRecord来处理,这个类没有实现任何接口,可见他和DefaultConfiguration是绑定在一起的。
1
internal class DefaultConfigurationSystem : IConfigurationSystem
2

{
3
// Methods
4
internal DefaultConfigurationSystem();
5
object IConfigurationSystem.GetConfig(string configKey);
6
void IConfigurationSystem.Init();
7
8
// Properties
9
internal static Uri AppConfigPath
{ get; }
10
internal static string MachineConfigurationFilePath
{ get; }
11
internal static string MsCorLibDirectory
{ get; }
12
13
// Fields
14
private ConfigurationRecord _application;
15
private const string ConfigExtension = "config";
16
private const string MachineConfigFilename = "machine.config";
17
private const string MachineConfigSubdirectory = "Config";
18
private const int MaxPathSize = 0x400;
19
}
20
事实上所有的配置文件的分析和获取都是在ConfiguationRecord里实现的,作为配置文件分析的第一步,正如我们经常做的一样->加载一个配置文件,这个方法公开为 Load(filename)。DefaultConfiguationSystem的Init()方法中用machine.config创建了一个 ConfiguationRecord对象,并将其作为父对象传递给当前程序的ConfiguationRecord对象,当然前提是当前程序有配置文件,比如myapp.config,然后再加载当前程序的配置文件,从而实现配置文件的继承。
void IConfigurationSystem.Init()


{
lock (this)

{
if (this._application == null)

{
ConfigurationRecord record1 = null;
string text1 = DefaultConfigurationSystem.MachineConfigurationFilePath;
Uri uri1 = DefaultConfigurationSystem.AppConfigPath;
this._application = record1 = new ConfigurationRecord();
bool flag1 = record1.Load(text1);
if (!flag1 || (uri1 == null))

{
return;
}
this._application = new ConfigurationRecord(record1);
this._application.Load(uri1.ToString());
}
}
}
现在我们可以专注于ConfiguationRecord的具体实现了,Load方法中得到一个XmlTextWriter,并执行.ScanFactoriesRecursive和ScanSectionsRecursive方法。
reader1 = ConfigurationRecord.OpenXmlTextReader(filename);
if (reader1 != null)

{
this.ScanFactoriesRecursive(reader1);
if (reader1.Depth == 1)

{
this.ScanSectionsRecursive(reader1, null);
}
return true;
}
ScanFactoriesRecursive方法会调用他的一个重载方法来解析中的< sectionGroup>,,,,我们写配置文件时大小写可不能写错哦,.NET没有做toslower之类的转换,直接就是 “== “。在这个方法里程序会将解析得到的sectiongroup以key=tagkey,value= ConfigurationRecord.GroupSingleton的方式存到EnsureFactories里,将section以key= tagkey,value=typestring的方式储存,值得注意的是,这里并没有创建实现 IConfigurationSectionHandler的实例对象,而是将其类型名(比如:字符串” system.Configuration.NameValueSectionHandler”)作为值到EnsureFactories,等到后面 GetConfig的时候再来反射创建。则存为 ConfigurationRecord.RemovedFactorySingleton。就清空 EnsureFactories。这里的tagkey是各级name的组合,比如”mygroup/mysection”这样以分隔符”/”组合的形式。应该客观地说这部分代码用了很多goto语句,可读性不是太好,但这样写也确实没有什么问题。
this.CheckRequiredAttribute(text3, "name", reader);
this.CheckRequiredAttribute(text4, "type", reader);
this.VerifySectionName(text3, reader);
string text5 = ConfigurationRecord.TagKey(configKey, text3);
if (this.HaveFactory(text5) != ConfigurationRecord.HaveFactoryEnum.NotFound)

{

objArray1 = new object[]
{ text3 } ;
throw this.BuildConfigError(SR.GetString("Tag_name_already_defined", objArray1), reader);
}
this.EnsureFactories[text5] = text4;
goto Label_02B6;
ScanSectionsRecursive方法会解析配置文件里的section实例,并将其tagkey储存到Hashtable _unevaluatedSections中,表示尚未evaluated的configkey的集合,可见section实例对象的创建和 handler一样,都是fetch when need。在后面的操作Getconfig中会使用他。
if (this._unevaluatedSections == null)

{
this._unevaluatedSections = new Hashtable();
}
&
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-343236/
,如需转载,请注明出处,否则将追究法律责任。