Search code examples
c#.netcachingenterprise-library

Set maximum life of entity in Enterprise library's cache block?


In my application I want to add some items to my cache, but these items should be at most one day old.

Is there an OOTB way to set the maximum life for certain objects?


Solution

  • You can specify the expiration of your item when you add it to the cache using the Add method of the CacheManager:

    public void Add (
        string key,
        Object value,
        CacheItemPriority scavengingPriority,
        ICacheItemRefreshAction refreshAction,
        params ICacheItemExpiration[] expirations
    )
    


    In this admittedly far fetched example, if the product price is less than 100 then the product will be cached for 24 hours, otherwise it will expire 1 minute after its last access time from the cache.

    Product[] products = GetProducts();
    
    CacheManager cache = CacheFactory.GetCacheManager();
    
    AbsoluteTime twentyFourHoursLater = new AbsoluteTime(DateTime.Now.AddHours(24));
    SlidingTime oneMinuteSlidingTime = new SlidingTime(TimeSpan.FromMinutes(1));
    
    foreach (Product product in products)
    {
        if (product.ProductPrice < 100)
        {
            cache.Add(product.ProductID, product, CacheItemPriority.Normal, null,
                twentyFourHoursLater);
        }
        else
        {
            cache.Add(product.ProductID, product, CacheItemPriority.Normal, null,
                oneMinuteSlidingTime);
        }
    }