CacheProvider.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Globalization;
  3. namespace Infrastructure.Cache
  4. {
  5. /// <summary>
  6. /// 缓存工厂
  7. /// <para>李玉宝新增于2016-11-09 9:42:52</para>
  8. /// </summary>
  9. public abstract class CacheProvider : IDisposable
  10. {
  11. /// <summary>
  12. /// 缓存组件
  13. /// </summary>
  14. public ICacheContext CacheContext { get; private set; }
  15. /// <summary>
  16. /// 动态设置缓存对象的新实例
  17. /// </summary>
  18. /// <param name="cacheContext">缓存实例对象</param>
  19. public void SetCacheInstance(ICacheContext cacheContext)
  20. {
  21. //先释放现有的缓存组件
  22. if (CacheContext != null)
  23. {
  24. CacheContext = null;
  25. }
  26. //初始化缓存组件新的实例
  27. CacheContext = cacheContext;
  28. }
  29. public void SetCacheInstance(Type cacheContextType)
  30. {
  31. if (cacheContextType == null)
  32. {
  33. throw new ArgumentNullException("cacheContextType");
  34. }
  35. if (!typeof(ICacheContext).IsAssignableFrom(cacheContextType))
  36. {
  37. throw new ArgumentException(
  38. string.Format(CultureInfo.CurrentCulture, "该类型 {0} 必须继承自抽象类CacheContext", cacheContextType),
  39. "cacheContextType");
  40. }
  41. try
  42. {
  43. CacheContext = Activator.CreateInstance(cacheContextType) as ICacheContext;
  44. }
  45. catch (Exception ex)
  46. {
  47. throw new InvalidOperationException(
  48. String.Format(
  49. CultureInfo.CurrentCulture,
  50. "创建抽象类 CacheContext 的实例 {0} 失败",
  51. cacheContextType),
  52. ex);
  53. }
  54. }
  55. public void Dispose()
  56. {
  57. }
  58. }
  59. }