自定义配置文件读取

  配置文件用处很多,最开始使用是在数据分页数量当中。其次接触是在NHibernate当中。抽象工厂+配置文件是一个很好的应用。通过接口+配置文件,可以很方便的实现开放封闭原则。

  配置文件分为:元素,元素集合,节。

  元素: 

public class PersistenceElement : ConfigurationElement
{
[ConfigurationProperty(ConfigName.PropertyName, IsKey
= true, IsRequired = true)]
public string EntityClass
{
get
{
return (string)this[ConfigName.PropertyName];
}
set
{
this[ConfigName.PropertyName] = value;
}
}

[ConfigurationProperty(ConfigName.PropertyValue, IsRequired
= true)]
public string PersistenceClass
{
get
{
return (string)this[ConfigName.PropertyValue];
}
set
{
this[ConfigName.PropertyValue] = value;
}
}
}

   元素集合:

public class PersistenceElementCollenction : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new PersistenceElement();
}

protected override object GetElementKey(ConfigurationElement element)
{
return ((PersistenceElement)element).EntityClass;
}

public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}

protected override string ElementName
{
get { return ConfigName.PersistenceElement; }
}

public PersistenceElement this[int index]
{
get { return (PersistenceElement)this.BaseGet(index); }
set
{
if (this.BaseGet(index) != null)
{
this.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}

public new PersistenceElement this[string interfaceShortTypeName]
{
get { return (PersistenceElement)this.BaseGet(interfaceShortTypeName); }
}

public bool ContainsKey(string keyName)
{
bool result = false;
object[] keys = this.BaseGetAllKeys();
foreach (object key in keys)
{
if ((string)key == keyName)
{
result
= true;
break;

}
}
return result;
}
}

  节:

public class PersistenceProperty : ConfigurationSection
{
[ConfigurationProperty(ConfigName.PersistenceElementCollection,
IsDefaultCollection
= true)]
public PersistenceElementCollenction GetElementCollection
{
get { return (PersistenceElementCollenction)base[ConfigName.PersistenceElementCollection]; }
}
}

  配置文件的书写方式如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="PersistenceSection" type="Configuration.PersistenceProperty, Configuration"/>
</configSections>
<PersistenceSection>
<Persistences>
<Persistence PropertyName="A1" PropertyValue="A1Factory"></Persistence>
<Persistence PropertyName="A2" PropertyValue="A2Factory"></Persistence>
<Persistence PropertyName="A3" PropertyValue="A3Factory"></Persistence>
</Persistences>
</PersistenceSection>
</configuration>

  总结:通过配置文件我们可以动态的加载应用程序集。从而实现开放封闭原则。

下载源代码:文件下载

posted @ 2010-06-20 22:47  13路易的  阅读(422)  评论(0编辑  收藏  举报