CacheHelper.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using DirectService.Tools;
  2. using JLHHJSvr.BLL;
  3. using JLHHJSvr.Com.Model;
  4. using LJLib;
  5. using LJLib.DAL.SQL;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Data.SqlClient;
  10. using System.Linq;
  11. using System.Reflection;
  12. namespace JLHHJSvr.Helper
  13. {
  14. internal sealed class CacheHelper : HelperBase
  15. {
  16. #region 基础资料Mapping
  17. /// <summary>
  18. /// 弹簧资料
  19. /// </summary>
  20. public class SpringMapping : ICacheMapping<int, u_spring>
  21. {
  22. public u_spring GetInstance(SqlCommand cmd, int springid)
  23. {
  24. var instance = new u_spring() { springid = springid };
  25. DbSqlHelper.SelectOne(cmd, instance, "line_diameter,gram_weight,height,center_diameter,caliber,cyclenum,roll_width,roll_length,arrangement_width,arrangement_height,springtypeid");
  26. return instance;
  27. }
  28. }
  29. /// <summary>
  30. /// 部门资料
  31. /// </summary>
  32. public class DeptMapping : ICacheMapping<int, u_dept>
  33. {
  34. public u_dept GetInstance(SqlCommand cmd, int deptid)
  35. {
  36. var instance = new u_dept() { deptid = deptid };
  37. DbSqlHelper.SelectOne(cmd, instance, "pricelistid,profitrate,moneyrate,discount,taxes_rate,managerate,com_profitrate,dannum1_rate,dannum2_rate,dannum3_rate,dannum4_rate");
  38. return instance;
  39. }
  40. }
  41. #endregion
  42. #region 获取数据
  43. private static readonly Dictionary<Type, object> _cacheServiceRegistry = new Dictionary<Type, object>();
  44. public TEntity GetData<TEntity,TMapping>(object key)
  45. where TEntity : class, new()
  46. where TMapping : new()
  47. {
  48. var mappingType = typeof(TMapping);
  49. var iface = mappingType.GetInterfaces()
  50. .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICacheMapping<,>));
  51. if (iface == null) throw new InvalidOperationException($"{mappingType.Name} must implement ICacheMapping<TKey, TValue>");
  52. var genericArgs = iface.GetGenericArguments();
  53. var keyType = genericArgs[0];
  54. // 找到私有的强类型实现方法并用 MakeGenericMethod 构造
  55. var method = typeof(CacheHelper).GetMethod(nameof(GetDataInternal), BindingFlags.Instance | BindingFlags.NonPublic);
  56. var gm = method.MakeGenericMethod(keyType, typeof(TEntity), mappingType);
  57. // 调用并返回(Invoke 返回 object)
  58. return (TEntity) gm.Invoke(this, new object[] { key });
  59. }
  60. private TValue GetDataInternal<TKey, TValue, TMapping>(object key)
  61. where TMapping : ICacheMapping<TKey, TValue>, new()
  62. where TValue : class, new()
  63. {
  64. var mapping = new TMapping();
  65. return mapping.GetInstance(cmd, (TKey)key);
  66. }
  67. #endregion
  68. }
  69. }