c#特性加反射實現解耦
阿新 • • 發佈:2019-01-23
private Dictionary<string, IBean> beanObjcetDic = new Dictionary<string, IBean>(); /// <summary> /// 載入全部的業務物件 /// </summary> private void LoadAllBeanObject() { try { //獲取本程式集下實現IBean介面的全部業務物件例項。 Assembly ModelBuilderAbly = Assembly.GetExecutingAssembly(); Type[] types = ModelBuilderAbly.GetTypes(); foreach (Type type in types) { //如果當前型別實現了IBean介面 if (type.GetInterface("IBean") != null) { //檢索應用與指定成員的指定型別的自定義特性 BeanAttribute theBeanAttri = type.GetCustomAttribute(typeof(BeanAttribute)) as BeanAttribute; //並且定義了業務標記 if (theBeanAttri != null) { //新增到業務構造器例項字典 IBean beanObj = Activator.CreateInstance(type) as IBean; if (beanObj != null) { //1.呼叫業務物件的初始化方法,完成初始化 beanObj.Init(); //2.將初始化完畢的業務物件,新增到業務物件字典中 beanObjcetDic.Add(theBeanAttri.BeanName, beanObj); } } } } } catch (Exception e) {//系統日誌 loger.WriteLog("BeanManager.LoadAllBeanObject", e, LogLevel.Error, typeof(BeanManager)); } }