[英]Reading custom configuration from web.config return null
我試圖從數據庫/添加元素中讀取值,但是每次都會拋出異常。 這里怎么了...我不明白。
如果這是一個線索,則此代碼在其自己的程序集中。
在web.config中配置
<sectionGroup name="sessionFactoryConfiguration">
<section name="Databases" type="Boot.Multitenancy.Configuration.SessionFactoryConfiguration, ConfigurationCollectionAttribute"/>
</sectionGroup>
<sessionFactoryConfiguration>
<Databases>
<add name="www.domain.com" autoPersist="true" dbType="SqlCe"/>
<add name="www.domain.net" autoPersist="true" dbType="SqlCe"/>
</Databases>
</sessionFactoryConfiguration>
嘗試從該部分獲取值。 一世
var conf = ConfigurationManager.GetSection("Databases") as SessionFactoryConfiguration;
if (conf == null)
throw new Exception("Not loaded"); //Throws exception each time.
執行部分。
public class DatabaseSection : ConfigurationElement
{
public DatabaseSection() { }
public DatabaseSection(String name, bool autoPersist, DbType dbtype)
{
this.Name = name;
this.AutoPersist = autoPersist;
this.DbType = dbtype;
}
[ConfigurationProperty("name")]
public String Name
{
get { return (String)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("autoPersist", DefaultValue = false, IsRequired = false)]
public Boolean AutoPersist
{
get { return (Boolean)this["autoPersist"]; }
set { this["autoPersist"] = value; }
}
/// <summary>
/// DbType
/// </summary>
[ConfigurationProperty("dbType", DefaultValue = DbType.SqlCe, IsRequired = false)]
public DbType DbType
{
get { return (DbType)this["dbType"]; }
set { this["dbType"] = value; }
}
}
ConfigurationCollection屬性已添加到類。
public class SessionFactoryConfiguration : ConfigurationSection
{
[ConfigurationProperty("Databases", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(DatabaseCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
public DatabaseCollection Databases
{
get { return (DatabaseCollection)base["Databases"]; }
}
}
public class DatabaseCollection : ConfigurationElementCollection
{
public DatabaseCollection()
{
Add((DatabaseSection)CreateNewElement());
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
}
protected override ConfigurationElement CreateNewElement()
{
return new DatabaseSection();
}
....//long code
}
如此簡單...我只需要在Web配置中將ConfigurationCollectionAttribute更改為我的AssemblyName ...
在每個示例中,他們都引用此屬性...
來自:節名稱=“ sessionFactoryConfiguration” type =“ Boot.Multitenancy.Configuration.SessionFactoryConfiguration,ConfigurationCollectionAttribute” />
若要:部分名稱=“ sessionFactoryConfiguration”類型=“ Boot.Multitenancy.Configuration.SessionFactoryConfiguration,Boot.Multitenancy” />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.