Click here to Skip to main content
Click here to Skip to main content

Simple cache object and cache dictionary

, 3 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ronen Rabinovitz
Team Leader
Israel Israel
No Biography provided

Comments and Discussions

 
QuestionI like it PinmemberFatCatProgrammer5-Jun-12 6:02 
Questionhi Pinmemberbeleshi3-Jun-12 23:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140718.1 | Last Updated 3 Jun 2012
Article Copyright 2012 by Ronen Rabinovitz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid