CacheHelper.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. using System.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Bowin.Common.Utility;
  9. namespace Bowin.Common.Cache
  10. {
  11. public static class CacheHelper
  12. {
  13. public static void UseCache<T>(this IServiceCollection service) where T : class, ICacheProvider, new()
  14. {
  15. service.AddSingleton<ICacheProvider, T>();
  16. CacheProvider.Config<T>(service);
  17. }
  18. public static object Add(string key, object entry)
  19. {
  20. ICacheProvider cacheProvider = HttpHelper.GetService<ICacheProvider>();
  21. if (cacheProvider == null)
  22. {
  23. throw new Exception("请在Startup先指定缓存类型。");
  24. }
  25. return cacheProvider.Add(key, entry);
  26. }
  27. public static object Add(string key, object entry, DateTime utcExpiry)
  28. {
  29. ICacheProvider cacheProvider = HttpHelper.GetService<ICacheProvider>();
  30. if (cacheProvider == null)
  31. {
  32. throw new Exception("请在Startup先指定缓存类型。");
  33. }
  34. return cacheProvider.Add(key, entry, utcExpiry);
  35. }
  36. public static object Get(string key)
  37. {
  38. ICacheProvider cacheProvider = HttpHelper.GetService<ICacheProvider>();
  39. if (cacheProvider == null)
  40. {
  41. throw new Exception("请在Startup先指定缓存类型。");
  42. }
  43. return cacheProvider.Get(key);
  44. }
  45. public static void Remove(string key)
  46. {
  47. ICacheProvider cacheProvider = HttpHelper.GetService<ICacheProvider>();
  48. if (cacheProvider == null)
  49. {
  50. throw new Exception("请在Startup先指定缓存类型。");
  51. }
  52. cacheProvider.Remove(key);
  53. }
  54. public static void Set(string key, object entry)
  55. {
  56. ICacheProvider cacheProvider = HttpHelper.GetService<ICacheProvider>();
  57. if (cacheProvider == null)
  58. {
  59. throw new Exception("请在Startup先指定缓存类型。");
  60. }
  61. cacheProvider.Set(key, entry);
  62. }
  63. public static void Set(string key, object entry, DateTime utcExpiry)
  64. {
  65. ICacheProvider cacheProvider = HttpHelper.GetService<ICacheProvider>();
  66. if (cacheProvider == null)
  67. {
  68. throw new Exception("请在Startup先指定缓存类型。");
  69. }
  70. cacheProvider.Set(key, entry, utcExpiry);
  71. }
  72. }
  73. }