using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Text; using QWPlatform.SystemLibrary.LogManager; using QWPlatform.SystemLibrary.Utils; namespace PMS.Interface { /// /// 创 建 人:王海洋 /// 创建日期:2018-12-10 /// 功能描述:接口实例化工厂处理类 /// public class InterfaceFactory { //缓存实例,如果在缓存中存在,直接返回 private static ConcurrentDictionary _cacheObject = new ConcurrentDictionary(); //private static Assembly businessAssembly = null; private static object locker = new object(); /// /// 创建一个实例化工厂 /// /// 指定泛型的接口 /// public static T CreateBusinessInstance() where T : class { var obj = default(T); var t = typeof(T); var hashCode = t.GetHashCode(); if (_cacheObject.ContainsKey(hashCode)) {//缓存中存在。 return _cacheObject[hashCode] as T; } else {//重新创建实例 obj = CreateInstance(); if (obj != null && !_cacheObject.ContainsKey(hashCode)) {//添加到缓存中 _cacheObject.TryAdd(hashCode, obj); } else { //throw new NotImplementedException("业务对象创建为空:" + t.FullName); Logger.Instance.Error("业务对象创建为空"); } }//end return obj; } //创建实例 private static T CreateInstance() where T : class { var obj = default(T); var t = typeof(T); try { var appPath = Path.Combine(Strings.AppDomainPath, "ZLSoft.PMS.BusinessService.dll"); if (!File.Exists(appPath)) {//未找到业务体dll throw new FileNotFoundException("未找到业务实现dll文件", appPath); } var businessAssembly = Assembly.Load("ZLSoft.PMS.BusinessService"); var type = businessAssembly.GetTypes().First(p => p.GetInterface(t.Name) != null); if (type != null) { obj = (T)businessAssembly.CreateInstance(type.FullName); } return obj; //var types = businessAssembly.GetTypes(); //foreach (var type in types) //{ // var itype = type.GetInterface(t.Name); // if (itype != null) // {//找到实现的实体类 // obj = Activator.CreateInstance(type) as T; // // obj = businessAssembly.CreateInstance(type.FullName) as T; // if (obj != null) // {//已到相应的实例,退出循环 // return obj; // } // else // { // throw new QWPlatform.SystemLibrary.CustomException.DataConvertException("创建的业务实例为空对象", type.FullName, null); // } // }//end if //}//end foreach } catch (Exception ex) { Logger.Instance.Error("加载业务实现DLL异常", ex); throw new NotImplementedException("业务DLL没实现了最新定义的接口,可以尝试将业务层PMS.BusinessService.dll复制到运行的Bin目录下。" + ex.Message); } } /// /// 将所有实例对象清空 /// public static void ClearCache() {//清空缓存 _cacheObject.Clear(); } } }