Storing NULLS in Enterprise Library Caching Block, maybe I want my NULL..

I am retrieving data where a NULL is quite a valid value to store. I am doing database retrievals and if the records/objects don’t exist in the database, then I don’t want another roundtrip each time simply because I think the data expired.

So, it’s not often this is a valid scenario, but when you need to store a NULL as a value that is cached then there is an easy approach.
I created a class to handle the storage of my actual values here:

/// Class to help with caching a NULL value, and knowing its really null.
public  class NullCacheItem<>
{
     /// Gets or sets the value.
     public T Value { get; set; }
     /// Gets a value indicating whether this instance is null.
     public bool IsNull
     {
          get { return Value == null; }
     }
}

The class above is a generic/template class that allows you to pass in the actual object type you are using in your cache. This makes it much easier to consume.
NOTE: Why not use the Nullable Template i.e. DateTime? . Well, I designed this for reference objects. Not for primitives. ? doesn’t work for nullable objects silly!

So, now in your code you can easily use this model. Below is some sample code.

public ConfigurationSection GetSection(string sectionName)
{
     var cacheSection = sectionCache.GetData(sectionName) as NullCacheItem<ConfigurationSection>;

     if (cacheSection == null)
     {
          try
          {
               lock (cacheLock)
               {
                    cacheSection = sectionCache.GetData(sectionName) as NullCacheItem<ConfigurationSection>;
                    if (cacheSection == null)
                    {
                         cacheSection = new NullCacheItem<ConfigurationSection>()
                         {
                              Value = SqlConfigurationManager.GetSection(sectionName, data) as ConfigurationSection
                         };

                    sectionCache.Add(cacheSection,
                         new AbsoluteCacheExpiration(new TimeSpan(0, _sectionCacheTimeout, 0)),
                         sectionName);
                    }
               }
          }
          catch (Exception ex)
          {
               // handle internal exception
               ExceptionManager.HandleException(ex);
          }
     }

     if (cacheSection != null)
          if (!cacheSection.IsNull)
               return cacheSection.Value;
     return null;
}

It’s very easy to implement and adds a lot of value.

Note: The above is real world code using the object. This provides the spirit of the code, but is not just copy paste run code.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *