namespace Model
{
public class MapperFactory
{
//声明一个ISqlMapper接口类型的数据映射器 _mapper,其初始值为null
private static volatile ISqlMapper _mapper = null;
//private static log4net.Appender.AdoNetAppender adoApd = null;
static MapperFactory()
{
RefreshMapperSetting();
}
/// <summary>
/// 监视变化,并提供变化后的处理方法
/// </summary>
/// <param name="obj"></param>
protected static void Configure(object obj)
{
//将数据映射器初始值置空
_mapper = null;
}
/// <summary>
/// 定义InitMapper方法-用于创建sql数据映射器
/// </summary>
protected static void InitMapper()
{
RefreshMapperSetting();
}
public static void RefreshMapperSetting()
{
//调用委托ConfigureHandler,创建委托变量handler
//用于SqlMap.config改变后的处理方法
ConfigureHandler handler = new ConfigureHandler(Configure);
//新建一个DomSqlMapBuilder类的实例builder
//此变量用于配置和监视SqlMap.config的变化
DomSqlMapBuilder builder = new DomSqlMapBuilder();
//加入程序中自定义的键值对
//你可以在配置监视之前加上自己的一些键值对内容
NameValueCollection nvcProperties = new NameValueCollection();
nvcProperties.Add("DataSource", "PACTERA_GZF-PC");
nvcProperties.Add("DataBase", "TestOne");
nvcProperties.Add("UserName", "sa");
nvcProperties.Add("Password", "sa");
nvcProperties.Add("Timeout", "60");
builder.Properties = nvcProperties;
//启用在配置之前的检查
builder.ValidateSqlMapConfig = true;
//使用builder的ConfigureAndWatch生成一个ISqlMapper类型的数据映射器
_mapper = builder.ConfigureAndWatch("SqlMap.config", handler);
}
/// <summary>
/// 定义一个返回值为接口类型的方法Instance,用于实现sqlMapper实例化
/// </summary>
/// <returns></returns>
public static ISqlMapper Instance()
{
if (_mapper == null)
{
lock (typeof(SqlMapper))
{
if (_mapper == null) // double-check
{
//引用InitMapper,创建sqlMapper实例
InitMapper();
}
}
}
return _mapper;
}
/// <summary>
/// 定义一个Get方法,返回_mapper
/// </summary>
/// <returns></returns>
public static ISqlMapper Get()
{
return Instance();
}
}
}