using SKMC.Api.Common.Logger; using System; using System.Collections.Generic; namespace SKMC.Api.Common { /// ///

接口工厂

///
类似IOC容器, 可将接口与实例注册绑定, 在需要调用接口时获取实例
///
Resolve获取单例, Create创建新实例
///
public class ObjectFactory { private static readonly ILogger log = LogFactory.Get(); private static readonly Dictionary> container = new Dictionary>(); /// /// 注册接口实例 /// /// /// /// public static void Register(object obj, string name = "default") { Type type = typeof(T); if (!container.ContainsKey(type)) { container[type] = new Dictionary(); } //else //{ // throw new SystemException($"Register Failed, Cannot Register SameType: {type.Name}"); //} container[type][name] = obj; log.Debug($"Register {type.Name} success"); } /// /// 反注册接口实例, 重复注册前需要反注册 /// /// public static void UnRegister() { Type type = typeof(T); if (container.ContainsKey(type)) { bool result = container.Remove(type); log.Debug($"UnRegister Type: {type.Name}: {result}"); } } /// /// 解析接口实例(单例) /// /// /// /// public static T Resolve(string name = "default") { Type type = typeof(T); if (container.ContainsKey(type) && container[type].ContainsKey(name)) { object obj = (T)container[type][name]; //log.Debug($"Create {type.Name} success, obj: {obj.GetHashCode()}"); return (T)obj; } throw new SystemException($"Resolve Faild, No object for [{type}] with name [{name}] found."); } /// /// 创建接口实例(多例) /// /// /// /// public static T Create(string name = "default") { Type type = typeof(T); if (container.ContainsKey(type) && container[type].ContainsKey(name)) { object objectNow = container[type][name]; object objectNew = Activator.CreateInstance(objectNow.GetType()); //log.Debug($"Create {type.Name} success, obj: {objectNew.GetHashCode()}"); return (T)objectNew; } throw new SystemException($"Create Faild, No object for [{type}] with name [{name}] found."); } } }