New Cache() extension - let it be parameters sensitive?
The new Cache() extension is absolutely great feature. One caveat though is that it is not parameters sensitive and it might be misleading in some cases.
A very simplified example:
int userID = 7;
Users.Where(u => u.UserID == userID).Cache().FirstOrDefault().Dump();
When I run it - I get the expected user entity.
Now, if I change userID to 8, and I forgot I used Cache(), I will still get the user with ID 7, and I might execute a wrong logic.
To handle that - I use Cache(string) method with key which is combined by the relevant parameters for that query.
Anyway to implement Cache() with parameters sensitivity?
Thanks,
Shlomi
-
james.manning commented
Seems like it's a chicken-and-egg problem - if you're not going to pass in the identifying info (cache key), then how would the Cache method know whether it can/should return the cached object or not? Seems like the only option would be executing the code again, negating the value of the cache.
If you find that you do this often (caching different particular rows at different times), then you might want to instead cache a dictionary or the like so you can index into it and be more explicit about the item you're wanting to fetch from the cache? Admittedly, at that point you're reinventing the cache key, so I'd say if you have problems with mentally keeping track of what Cache is currently holding, then just never use the no-params overload and always be explicit in what you're caching by key name :)
-
Shlomi commented
After playing with Cache() - I have to say that it is quite dangerous in some cases. The fact that it is not parameters sensitive might be very misleading and give wrong results because of the cache.
I know that I should know what I'm doing when using it, but sometimes you forget and get burned.For your consideration.