using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using Zhaizj.Framework.Utils;
namespace Zhaizj.Framework.Config.DotNetConfig
{
///
/// 配置组(依赖 .NET的配置架构)
///
///
///
/// <configSections>
/// <sectionGroup name="KEB.devfx" type="KEB.DevFx.Config.DotNetConfig.GroupHandler, KEB.DevFx.BaseFx">
/// <section name="mail" type="KEB.DevFx.Utils.Mail.Config.SectionHandler, KEB.DevFx.BaseFx" />
/// ......
/// </sectionGroup>
/// </configSections>
///
/// ......
///
/// <KEB.devfx>
/// <mail>
/// <smtpSetting server="" port="" userName="" password="" />
/// </mail>
/// </KEB.devfx>
/// ......
///
///
public class GroupHandler : ConfigurationSectionGroup
{
private static GroupHandler instance;
private static bool isInit;
private static bool isWebApp;
private static Dictionary sectionCache;
private static readonly object lockObject = new object();
private static void Init(bool throwOnError) {
if (isInit) {
return;
}
Configuration config;
if (HttpContext.Current != null) {
isWebApp = true;
config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
} else {
isWebApp = false;
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
foreach (string key in config.SectionGroups.Keys) {
ConfigurationSectionGroup csg = config.SectionGroups[key];
if(csg == null || string.IsNullOrEmpty(csg.Type)) {
continue;
}
Type csgType = TypeHelper.CreateType(csg.Type, false);
if (csgType == typeof(GroupHandler)) {
break;
}
}
sectionCache = new Dictionary();
if (instance == null) {
isInit = true;
if (throwOnError) {
throw new Exception("配置组未正确配置");
}
return;
}
foreach (ConfigurationSection section in instance.Sections) {
string sectionTypeName = section.SectionInformation.Type;
string sectionName = section.SectionInformation.SectionName;
Type sectionType = TypeHelper.CreateType(sectionTypeName, false);
object objectSection;
if (isWebApp) {
objectSection = WebConfigurationManager.GetSection(sectionName);
} else {
objectSection = ConfigurationManager.GetSection(sectionName);
}
if (objectSection != null) {
sectionCache.Add(sectionType, (ConfigurationSection)objectSection);
}
}
isInit = true;
}
///
/// 当前配置组的实例(单件)
///
public static GroupHandler Instance {
get { return instance; }
}
///
/// 获取配置节(泛型)
///
/// 配置节类型
/// 配置节
public static T GetSection() where T : ConfigurationSection {
return GetSection(true);
}
///
/// 获取配置节(泛型)
///
/// 配置节类型
/// 如果配置组未配置是否抛出异常
/// 配置节
public static T GetSection(bool throwOnError) where T : ConfigurationSection {
if (!isInit) {
lock (lockObject) {
if (!isInit) {
Init(throwOnError);
}
}
}
Type type = typeof(T);
ConfigurationSection sectionObject;
sectionCache.TryGetValue(type, out sectionObject);
return sectionObject as T;
}
///
/// 构造方法
///
protected GroupHandler() {
instance = this;
}
}
}