使用C#的反射機(jī)制時(shí)遇到的問題

字號:

項(xiàng)目DALFactory是采用工廠模式設(shè)計(jì)的,設(shè)計(jì)模式的書我也曾看過Java的設(shè)計(jì)模式,理解也不太深刻,但對工廠模式還是較為熟悉,使用它可以根據(jù)需求返回不同的實(shí)例對象,在DALFactory項(xiàng)目中使用反射機(jī)制來實(shí)現(xiàn)依賴注入,當(dāng)然,它的實(shí)現(xiàn)還是沒有java中的spring那樣靈活,強(qiáng)大,部分代碼如下:
    // <summary>
    /// 抽象工廠模式創(chuàng)建DAL。
    /// Web.config 需要加入配置:(利用工廠模式+反射機(jī)制+緩存機(jī)制,實(shí)現(xiàn)動(dòng)態(tài)創(chuàng)建不同的數(shù)據(jù)層對象接口)
    /// DataCache類在導(dǎo)出代碼的文件夾里
    /// 可以把所有DAL類的創(chuàng)建放在這個(gè)DataAccess類里
    /// <appSettings>
    /// <add key="DAL" value="SmsSystem.SQLServerDAL" /> (這里的命名空間根據(jù)實(shí)際情況更改為自己項(xiàng)目的命名空間)
    /// </appSettings>
    /// </summary>
    public sealed class DataAccess
    {
    private static readonly string path = ConfigurationManager.AppSettings["DAL"];
    /// <summary>
    /// 創(chuàng)建對象或從緩存獲取
    /// </summary>
    public static object CreateObject(string path, string CacheKey)
    {
    object objType = DataCache.GetCache(CacheKey);//從緩存讀取
    if (objType == null)
    {
    try
    {
    //Assembly ass = new Assembly();
    objType = Assembly.Load(path).CreateInstance(CacheKey);//反射創(chuàng)建
    DataCache.SetCache(CacheKey, objType);// 寫入緩存
    }
    catch(System.Exception ex)
    {
    string str = ex.Message;//
    SmsSystem.Utility.SaveLog.SaveInfoToLog(str, "errorLog", "異常");
    }
    }
    return objType;
    }
    /// <summary>
    /// 不使用緩存,創(chuàng)建對象
    /// </summary>
    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;// 記錄錯(cuò)誤日志
    return null;
    }
    }
    /// <summary>
    /// 創(chuàng)建CustEmployee數(shù)據(jù)層接口
    /// </summary>
    public static SmsSystem.IDAL.ICustEmployee CreateCustEmployee()
    {
    string CacheKey = path + ".CustEmployee";
    object objType = CreateObject(path, CacheKey);
    return (ICustEmployee)objType;
    }
    ………………(其它數(shù)據(jù)層接口)
    }