public class SettingExceptionProvider
{
public static Dictionary<Type, ExceptionConfig> Container =
new Dictionary<Type, ExceptionConfig>();
static SettingExceptionProvider()
{
InitContainer();
}
//读取配置信息,初始化容器
private static void InitContainer()
{
var section = WebConfigurationManager.GetSection("settingException") as SettingExceptionSection;
if(section == null)
{
return;
}
InitFromGroups(section.Exceptions.Groups);
InitFromAddCollection(section.Exceptions.AddCollection);
}
private static void InitFromGroups(GroupCollection groups)
{
foreach (var group in groups.Cast<GroupElement>())
{
ExceptionConfig config = new ExceptionConfig();
config.View = group.View;
config.Handler = CreateHandler(group.Handler);
foreach(var item in group.AddCollection.Cast<AddElement>())
{
Exception ex = CreateException(item.Exception);
config.Exception = ex;
Container[ex.GetType()] = config;
}
}
}
private static void InitFromAddCollection(AddCollection collection)
{
foreach(var item in collection.Cast<AddElement>())
{
ExceptionConfig config = new ExceptionConfig();
config.View = item.View;
config.Handler = CreateHandler(item.Handler);
config.Exception = CreateException(item.Exception);
Container[config.Exception.GetType()] = config;
}
}
//根据完全限定名创建IExceptionHandler对象
private static IExceptionHandler CreateHandler(string fullName)
{
if(string.IsNullOrEmpty(fullName))
{
return null;
}
Type type = Type.GetType(fullName);
return Activator.CreateInstance(type) as IExceptionHandler;
}
//根据完全限定名创建Exception对象
private static Exception CreateException(string fullName)
{
if(string.IsNullOrEmpty(fullName))
{
return null;
}
Type type = Type.GetType(fullName);
return Activator.CreateInstance(type) as Exception;
}
}
以下是各个配置节点的信息:
settingExceptions节点:
/// <summary>
/// settingExceptions节点
/// </summary>
public class SettingExceptionSection : ConfigurationSection
{
[ConfigurationProperty("exceptions",IsRequired=true)]
public ExceptionsElement Exceptions
{
get
{
return (ExceptionsElement)base["exceptions"];
}
}
}
exceptions节点:
/// <summary>
/// exceptions节点
/// </summary>
public class ExceptionsElement : ConfigurationElement
{
private static readonly ConfigurationProperty _addProperty =
new ConfigurationProperty("", typeof(AddCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
[ConfigurationProperty("", IsDefaultCollection = true)]
public AddCollection AddCollection
{
get
{
return (AddCollection)base[_addProperty];
}
}
[ConfigurationProperty("groups")]
public GroupCollection Groups
{
get
{
return (GroupCollection)base["groups"];
}
}
}








