Page 283 - DCAP312_WEB_TECHNOLOGIES_II
P. 283
Unit 14: Debugging and Optimization
So, with our interface, or cache proxy, and also added a couple of additional helper methods. Notes
One helps us generate cache keys in a standardize format that takes, more or less, a hierarchical
approach to naming (more on that in a second). This particular approach is highly coupled to
the model hierarchy within the site/solution we are currently working on, but the pattern is
pretty simple:
public string GetCacheKey(string repoName, ObjectType type,
string? id)
{
return string.Format(“{0}::{1}->{2}”,
new object[] {repoName, type, id });
}
First, we just create a simple ObjectType Enum to list the three (in this case) different object
types “Single” objects (where the id is the id of the object itself), “Sets” of objects (where the id
is the id of the parent), and “All” where what’s being cached represents an entire collection of
objects, as is the case with the GetAllProducts() method, above.
The use of a constant to designate the repository name, along with wrapper methods to handle
cache Input and Output (as well as to make a cache provider neutral mapping for cache retention
priorities), yields an approach like this:
CacheProvider CacheProxy;
const string REPO_NAME = “Products”;
public ProductRepository(ICacheProvider provider)
{
this.CacheProxy = provider;
}
public List<Product> GetAllProducts()
{
string cacheKey =
CacheProxy.GetCacheKey(REPO_NAME, ObjectType.All, ““);
List<Product> output =
CacheProxy.Get(cacheKey) as List<Product>;
if (output == null)
{
output = db.Products
.Select()
.ToList();
CacheProxy.Add(cacheKey, output, CacheType.Keep);
}
return output;
}
Where standardized cache key entries get really cool though, is when it comes to updating,
removing, or adding new products or objects. Because my cache keys are standardized, if
add a new Product, the method that handles that addition can simply create a new cache key
for the repo-name with an Object Type of All and kick out just the collection of All Products.
Individual Products, however, remain cached because they’re all using different Cache Keys.
Likewise, however, they can be removed as needed by simply generating cache keys matching
their keys, and they will be dropped. So, for example, in a Repository method that Updates a
LOVELY PROFESSIONAL UNIVERSITY 277