using System;
using System.Reflection;
using System.Configuration;
using IDAL;
namespace DALFactory
{
/// <summary>
/// 抽象工厂模式创建DAL。
/// web.config 需要加入配置:(利用工厂模式+反射机制+缓存机制,实现动态创建不同的数据层对象接口)
/// DataCache类在导出代码的文件夹里
/// 可以把所有DAL类的创建放在这个DataAccess类里
/// <appSettings>
/// <add key="DAL" value="LiTianPing.SQLServerDAL" /> (这里的命名空间根据实际情况更改为自己项目的命名空间)
/// </appSettings>
/// </summary>
public sealed class DataAccess
{
private static readonly string path = ConfigurationManager.AppSettings["DAL"];
public DataAccess()
{ }
#region 创建对象
//不使用缓存
private static object CreateObjectNoCache(string path, string CacheKey)
{
try
{
object objType = Assembly.Load(path).CreateInstance(CacheKey);
return objType;
}
catch//(System.Exception ex)
{
//string str=ex.Message;// 记录错误日志
return null;
}
}
//使用缓存
private static object CreateObject(string path, string CacheKey)
{
object objType = DataCache.GetCache(CacheKey);
if (objType == null)
{
try
{
objType = Assembly.Load(path).CreateInstance(CacheKey);
//objType = Assembly.Load("sooyuu.SQLServerDAL").CreateInstance("sooyuu.SQLServerDAL.MCenter.userManage");
DataCache.SetCache(CacheKey, objType);// 写入缓存
}
catch//(System.Exception ex)
{
//string str=ex.Message;// 记录错误日志
}
}
return objType;
}
#endregion
#region 文章生成
public static IDAL.ICreateHtml CreateHtml()
{
string CacheKey = path + ".CreateHtml";
object objType = CreateObject(path, CacheKey);
return (ICreateHtml)objType;
}
#endregion
#region 手机频道生成
public static IDAL.Imobile Mobile()
{
string CacheKey = path + ".mobile";
object objType = CreateObject(path, CacheKey);
return (Imobile)objType;
}
#endregion
}
}