| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- using SKMC.Api.Common.Logger;
- using System;
- using System.Collections.Generic;
- namespace SKMC.Api.Common
- {
- /// <summary>
- /// <p>接口工厂</p>
- /// <br>类似IOC容器, 可将接口与实例注册绑定, 在需要调用接口时获取实例</br>
- /// <br>Resolve获取单例, Create创建新实例</br>
- /// </summary>
- public class ObjectFactory
- {
- private static readonly ILogger log = LogFactory.Get();
- private static readonly Dictionary<Type, Dictionary<string, object>> container = new Dictionary<Type, Dictionary<string, object>>();
- /// <summary>
- /// 注册接口实例
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obj"></param>
- /// <param name="name"></param>
- public static void Register<T>(object obj, string name = "default")
- {
- Type type = typeof(T);
- if (!container.ContainsKey(type))
- {
- container[type] = new Dictionary<string, object>();
- }
- //else
- //{
- // throw new SystemException($"Register Failed, Cannot Register SameType: {type.Name}");
- //}
- container[type][name] = obj;
- log.Debug($"Register {type.Name} success");
- }
- /// <summary>
- /// 反注册接口实例, 重复注册前需要反注册
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public static void UnRegister<T>()
- {
- Type type = typeof(T);
- if (container.ContainsKey(type))
- {
- bool result = container.Remove(type);
- log.Debug($"UnRegister Type: {type.Name}: {result}");
- }
- }
- /// <summary>
- /// 解析接口实例(单例)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="name"></param>
- /// <returns></returns>
- public static T Resolve<T>(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.");
- }
- /// <summary>
- /// 创建接口实例(多例)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="name"></param>
- /// <returns></returns>
- public static T Create<T>(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.");
- }
- }
- }
|