DALFactory

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

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值