Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple cache object and cache dictionary

0.00/5 (No votes)
3 Jun 2012 1  
No need for complex settings, just create an object or a dictionary and let the helpers handle the cache.

Introduction

I had to use something that is commonly used: caching different types of objects. To my surprise, there are lots of solutions out there, but all are very complicated, and because they are designed to handle a wide range of needs, it is required to define quite a few settings before using them.

In this solution my aim was to do it as simple as possible with minimum pre-settings to meet my goals.

Background

I created two very simple classes designed to help create a cache object and a cache dictionary.

When creating the objects (in the constructor) we define the source data for getting the objects. When we need to use the value, the cache object will check if the object is in the cache and if not it will call the Fill method.

Using the code

When we call:

var userName = _userName.Value;

CacheObject checks in the internal System.Runtime.Caching.MemoryCache object if the value exists: 

var cacheValue = _cache[string.Empty];

(string.Empty is just a dummy value.)

If the value is not in the cache, we will call:

cacheValue = _getValueFunc.Invoke();

We need to define the function getValueFunc in the CacheObject constructor. In this function we can call the service or a value resource.

In the constructor, we can also define the expiration time for the Cache object – after the expiration time is complete, CacheObject will call the getValueFunc again.

CacheDictionary is based on the same logic but the main difference is that in the constructor, we need to define a function that gets the key parameter of the dictionary and returns the value of the dictionary.

When the expiration is not defined in the constructor, CacheObject will take the default expiration value from the Properties.Settings.Default.DefaultCasheTimeoutSeconds value. So we can set this value in the config file for all applications.

Enjoy.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here