I have a lot of method and I need to put some of it in cache. but I don't want it edit each method.
how can I pass a dynamic method with return value as parameter? kindly check comments as some of my question in my code.
Thank you for advance.
private string GetUserName(string userId)
{
// how can I pass the method as parameter?
// Method is dynamic and can be any method with parameter(s) and return value
return CacheIt<string>(item => GetUserNameFromDb(userId));
}
private T CacheIt<T>(Action<T> action) // Im not sure if this an Action
{
var key = "UserInfo." + userId; // how can I get the value of the parameter?
var cache = MemoryCache.Default;
var value = (T) cache[key];
if (value != null)
return value;
value = action(); // how can I call the action or the method
var policy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(1, 0, 0) };
cache.Add(key, value, policy);
return value;
}
private string GetUserNameFromDb(string userId)
{
return "FirstName LastName";
}