標籤:
BLLFactory的對象統一調用規則
在我的架構裡面,所有的業務類調用都是以BLLFactory入口進行開始建立,傳遞業務對象進去即可建立,這種統一入口的方式能夠方便記憶,並減少代碼,更重要的是能夠很好把一些如緩衝規則、建立規則封裝起來,簡化代碼。BLLFactory的建立如下所示。
方法一:
using Globalegrow.Toolkit;using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;namespace Globalegrow.BLL{ /// <summary> /// 對業務類進行構造的工廠類 /// </summary> /// <typeparam name="T">業務物件類型</typeparam> public class BLLFactory<T> where T : class { private static Hashtable objCache = new Hashtable(); private static object syncRoot = new Object(); /// <summary> /// 建立或者從緩衝中擷取對應業務類的執行個體 /// </summary> public static T Instance { get { string CacheKey = typeof(T).FullName; T bll = (T)objCache[CacheKey]; if (bll == null) { lock (syncRoot) { if (bll == null) { Assembly assObj = Assembly.Load(typeof(T).Assembly.GetName().Name); object obj = assObj.CreateInstance(CacheKey); bll = obj as T; objCache.Add(typeof(T).FullName, bll); } } } return bll; } } }}
View Code
方法二:
using Globalegrow.Toolkit;using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;namespace Globalegrow.BLL{ /// <summary> /// 對業務類進行構造的工廠類 /// </summary> /// <typeparam name="T">業務物件類型</typeparam> public class BLLFactory<T> where T : class { private static object syncRoot = new Object(); /// <summary> /// /// </summary> public static T Instance { get { string CacheKey = typeof(T).FullName; lock (syncRoot) { T bll = Reflect<T>.Create(typeof(T).FullName, typeof(T).Assembly.GetName().Name); return bll; } } } }}
View Code
反射需要用到的擴充方法
using System.Collections;using System.Reflection;namespace Globalegrow.Toolkit{ public class Reflect<T> where T : class { private static Hashtable m_objCache = null; public static Hashtable ObjCache { get { if (m_objCache == null) { m_objCache = new Hashtable(); } return m_objCache; } } public static T Create(string sName, string sFilePath) { return Create(sName, sFilePath, true); } public static T Create(string sName, string sFilePath, bool bCache) { string CacheKey = sFilePath + "." + sName; T objType = null; if (bCache) { objType = (T)ObjCache[CacheKey]; //從緩衝讀取 if (!ObjCache.ContainsKey(CacheKey)) { Assembly assObj = CreateAssembly(sFilePath); object obj = assObj.CreateInstance(typeof(T).FullName); objType = (T)obj; ObjCache.Add(CacheKey, objType);// 寫入緩衝 將DAL內某個對象裝入緩衝 } } else { objType = (T)CreateAssembly(sFilePath).CreateInstance(CacheKey); //反射建立 } return objType; } public static Assembly CreateAssembly(string sFilePath) { Assembly assObj = (Assembly)ObjCache[sFilePath]; if (assObj == null) { assObj = Assembly.Load(sFilePath); if (!ObjCache.ContainsKey(sFilePath)) { ObjCache.Add(sFilePath, assObj);//將整個ITDB。DAL。DLL裝入緩衝 } } return assObj; } }}
View Code
調用:
var systemConfigBLL = BLLFactory<SystemConfigBLL>.Instance.GetDBServiceTime();
View Code
C# 通過反射執行個體化BLL商務邏輯層