Search code examples
c#asp.net-mvcunity-container

How to pass down the System.Web.Cache to my service layer


I am using unity for IOC.

In my service layer I want to use the System.Web.Cache in my class.

Should I just pass that as a parameter and Unity will automatically pass that as dependancy?

example:

public class UserService
{
   public UserService(System.Web.Caching.Cache cache)
   {
     _cache = cache;
   }
}

Solution

  • You should use System.Runtime.Caching. It is specially designed to handle caching of Object. NopCommerce has great implementation for this. You should created a CacheManager like:

    /// <summary>
        /// Cache manager interface
        /// </summary>
        public interface ICacheManager
        {
            /// <summary>
            /// Gets or sets the value associated with the specified key.
            /// </summary>
            /// <typeparam name="T">Type</typeparam>
            /// <param name="key">The key of the value to get.</param>
            /// <returns>The value associated with the specified key.</returns>
            T Get<T>(string key);
    
            /// <summary>
            /// Adds the specified key and object to the cache.
            /// </summary>
            /// <param name="key">key</param>
            /// <param name="data">Data</param>
            /// <param name="cacheTime">Cache time</param>
            void Set(string key, object data, int cacheTime);
    
            /// <summary>
            /// Gets a value indicating whether the value associated with the specified key is cached
            /// </summary>
            /// <param name="key">key</param>
            /// <returns>Result</returns>
            bool IsSet(string key);
    
            /// <summary>
            /// Removes the value with the specified key from the cache
            /// </summary>
            /// <param name="key">/key</param>
            void Remove(string key);
    
            /// <summary>
            /// Removes items by pattern
            /// </summary>
            /// <param name="pattern">pattern</param>
            void RemoveByPattern(string pattern);
    
            /// <summary>
            /// Clear all cache data
            /// </summary>
            void Clear();
        }
    

    And then you can implement the ICacheManager interface with MemoryCache or any other cache manager like RedisCache as below:

     /// <summary>
        /// Represents a MemoryCacheCache
        /// </summary>
        public partial class MemoryCacheManager : ICacheManager
        {
            protected ObjectCache Cache
            {
                get
                {
                    return MemoryCache.Default;
                }
            }
    
            /// <summary>
            /// Gets or sets the value associated with the specified key.
            /// </summary>
            /// <typeparam name="T">Type</typeparam>
            /// <param name="key">The key of the value to get.</param>
            /// <returns>The value associated with the specified key.</returns>
            public virtual T Get<T>(string key)
            {
                return (T)Cache[key];
            }
    
            /// <summary>
            /// Adds the specified key and object to the cache.
            /// </summary>
            /// <param name="key">key</param>
            /// <param name="data">Data</param>
            /// <param name="cacheTime">Cache time</param>
            public virtual void Set(string key, object data, int cacheTime)
            {
                if (data == null)
                    return;
    
                var policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
                Cache.Add(new CacheItem(key, data), policy);
            }
    
            /// <summary>
            /// Gets a value indicating whether the value associated with the specified key is cached
            /// </summary>
            /// <param name="key">key</param>
            /// <returns>Result</returns>
            public virtual bool IsSet(string key)
            {
                return (Cache.Contains(key));
            }
    
            /// <summary>
            /// Removes the value with the specified key from the cache
            /// </summary>
            /// <param name="key">/key</param>
            public virtual void Remove(string key)
            {
                Cache.Remove(key);
            }
    
            /// <summary>
            /// Removes items by pattern
            /// </summary>
            /// <param name="pattern">pattern</param>
            public virtual void RemoveByPattern(string pattern)
            {
                var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
                var keysToRemove = new List<String>();
    
                foreach (var item in Cache)
                    if (regex.IsMatch(item.Key))
                        keysToRemove.Add(item.Key);
    
                foreach (string key in keysToRemove)
                {
                    Remove(key);
                }
            }
    
            /// <summary>
            /// Clear all cache data
            /// </summary>
            public virtual void Clear()
            {
                foreach (var item in Cache)
                    Remove(item.Key);
            }
        }
    

    Review this NopCommerce link for more details. Register ICacheManager in Unity to create object for MemoryCacheManager and use it in your application. Happy coding :)