OperationManager.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Concurrent;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. using Aitex.Core.Util;
  7. namespace Aitex.Core.RT.OperationCenter
  8. {
  9. public class OperationManager : ICommonOperation
  10. {
  11. ConcurrentDictionary<string, Func<string, object[], bool>> _keyValueMap;
  12. Func<object, bool> _isSubscriptionAttribute;
  13. Func<MemberInfo, bool> _hasSubscriptionAttribute;
  14. public OperationManager()
  15. {
  16. }
  17. public void Initialize()
  18. {
  19. _keyValueMap = new ConcurrentDictionary<string, Func<string, object[], bool>>();
  20. _isSubscriptionAttribute = attribute => attribute is SubscriptionAttribute;
  21. _hasSubscriptionAttribute = mi => mi.GetCustomAttributes(false).Any(_isSubscriptionAttribute);
  22. OP.InnerOperationManager = this;
  23. }
  24. public void Subscribe<T>(T instance, string keyPrefix = null) where T : class
  25. {
  26. if (instance == null)
  27. throw new ArgumentNullException("instance");
  28. Traverse(instance, keyPrefix);
  29. }
  30. public void Subscribe(string key, Func<string, object[], bool> op)
  31. {
  32. if (string.IsNullOrWhiteSpace(key))
  33. throw new ArgumentNullException("key");
  34. if (_keyValueMap.ContainsKey(key))
  35. throw new Exception(string.Format("Duplicated Key:{0}", key));
  36. if (op == null)
  37. throw new ArgumentNullException("op");
  38. _keyValueMap[key] = op;
  39. }
  40. public bool DoOperation(string operation, params object[] args)
  41. {
  42. if (!_keyValueMap.ContainsKey(operation))
  43. {
  44. throw new ApplicationException("调用了未发布的接口" + operation);
  45. }
  46. _keyValueMap[operation](operation, args);
  47. return true;
  48. }
  49. public void Traverse(object instance, string keyPrefix)
  50. {
  51. Parallel.ForEach(instance.GetType().GetMethods().Where<MethodInfo>(_hasSubscriptionAttribute), fi =>
  52. {
  53. string key = Parse(fi);
  54. key = string.IsNullOrWhiteSpace(keyPrefix) ? key : string.Format("{0}.{1}", keyPrefix, key);
  55. //Subscribe(key, fi.Invoke(instance, );
  56. });
  57. }
  58. string Parse(MethodInfo member)
  59. {
  60. return _hasSubscriptionAttribute(member) ? (member.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute).Key : null;
  61. }
  62. public void Record(string chamberId, string operation)
  63. {
  64. }
  65. }
  66. }