Monday, June 10, 2013

Simple Cached Repository Wrapper

Also take a look at my followup posts:


This wrapper is a quick and handy way to quickly implement caching without moving a lot of code around.  It has limitations in growth and extensibility, especially when you want to start implementing special rules around different types, aggregates, and relationships.

This implementation uses the .Net 4.0 MemoryCache which is pretty nice.  It can be easily modified to use any other caching mechanism, such as Redis.

Lets start out with a simple repository - this is the class that retreives data from a back-end system such as a database or service:


Here is the cached repository wrapper:


The way it is used is to create your MemoryCache instance, wire up your IoC framework, and then replace your repository calls with the wrapper when you want to use caching.

One example for a quick test would like this: