You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CacheOutputConfiguration.cs 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Linq;
  3. using System.Net.Http;
  4. using System.Reflection;
  5. using System.Web.Http;
  6. using iiie.CacheControl.Business.CacheKey;
  7. using iiie.CacheControl.Business.OutputCache;
  8. namespace iiie.CacheControl.Business.HttpExtensions
  9. {
  10. public class CacheOutputConfiguration
  11. {
  12. private readonly HttpConfiguration _configuration;
  13. private OutputCacheType _cacheType;
  14. public CacheOutputConfiguration(HttpConfiguration configuration, OutputCacheType type)
  15. {
  16. _configuration = configuration;
  17. _cacheType = type;
  18. }
  19. private static ICacheKeyGenerator TryActivateCacheKeyGenerator(Type generatorType)
  20. {
  21. var hasEmptyOrDefaultConstructor =
  22. generatorType.GetConstructor(Type.EmptyTypes) != null ||
  23. generatorType.GetConstructors(BindingFlags.Instance | BindingFlags.Public)
  24. .Any(x => x.GetParameters().All(p => p.IsOptional));
  25. return hasEmptyOrDefaultConstructor
  26. ? Activator.CreateInstance(generatorType) as ICacheKeyGenerator
  27. : null;
  28. }
  29. public ICacheKeyGenerator GetCacheKeyGenerator(HttpRequestMessage request, Type generatorType)
  30. {
  31. generatorType = generatorType ?? typeof(ICacheKeyGenerator);
  32. object cache;
  33. _configuration.Properties.TryGetValue(generatorType, out cache);
  34. var cacheFunc = cache as Func<ICacheKeyGenerator>;
  35. var generator = cacheFunc != null
  36. ? cacheFunc()
  37. : request.GetDependencyScope().GetService(generatorType) as ICacheKeyGenerator;
  38. return generator
  39. ?? TryActivateCacheKeyGenerator(generatorType)
  40. ?? new DefaultCacheKeyGenerator();
  41. }
  42. public IOutputCache GetCacheOutputProvider(HttpRequestMessage request, object outputCacheData)
  43. {
  44. object cache;
  45. _configuration.Properties.TryGetValue(typeof(IOutputCache), out cache);
  46. var cacheFunc = cache as Func<IOutputCache>;
  47. var cacheOutputProvider = cacheFunc != null ? cacheFunc() : request.GetDependencyScope().GetService(typeof(IOutputCache)) as IOutputCache;
  48. if (cacheOutputProvider == null)
  49. {
  50. if (_cacheType == OutputCacheType.DataBase)
  51. {
  52. cacheOutputProvider = new DbOutputCache();
  53. ((DbOutputCache) cacheOutputProvider).ConnectionString = outputCacheData as string;
  54. }
  55. else
  56. cacheOutputProvider = new MemoryOutputCache();
  57. }
  58. return cacheOutputProvider;
  59. }
  60. }
  61. }