| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- 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.");
- }
- }
- }
|