Can I use a static cache Helper method in a NET MVC controller?
- by Euston
I realise there have been a few posts regarding where to add a cache check/update and the separation of concerns between the controller, the model and the caching code.
There are two great examples that I have tried to work with but being new to MVC I wonder which one is the cleanest and suits the MVC methodology the best? I know you need to take into account DI and unit testing.
Example 1 (Helper method with delegate)
...in controller
var myObject = CacheDataHelper.Get(thisID, () =>
WebServiceServiceWrapper.GetMyObjectBythisID(thisID));
Example 2 (check for cache in model class) in controller
var myObject = WebServiceServiceWrapper.GetMyObjectBythisID(thisID));
then in model class..............
if (!CacheDataHelper.Get(cachekey, out myObject)) {
//do some repository processing
// Add obect to cache CacheDataHelper.Add(myObject, cachekey);
}
Both use a static cache helper class but the first example uses a method signature with a delegate method passed in that has the name of the repository method being called. If the data is not in cache the method is called and the cache helper class handles the adding or updating to the current cache.
In the second example the cache check is part of the repository method with an extra line to call the cache helper add method to update the current cache.
Due to my lack of experience and knowledge I am not sure which one is best suited to MVC. I like the idea of calling the cache helper with the delegate method name in order to remove any cache code in the repository but I am not sure if using the static method in the controller is ideal?
The second example deals with the above but now there is no separation between the caching check and the repository lookup. Perhaps that is not a problem as you know it requires caching anyway?