For example, I have some repositories to grab some data I need:
Addressrepository.GetAddress(string para1, string para2)
UserRepository.GetUserDetail(string userName)
FinancialRepository.GetFinancialInfo(int userId)
To apply a cache aside pattern, I would like to do this:
Ideally I would like to write a generic helper class to do this for all data loading functions.Something like the cache aside pattern described here: https://blog.cdemi.io/design-patterns-cache-aside-pattern/
However, in my case, I need to pass different parameters to different methods. In this case, is it possible to use Func and pass different parameters?
I checked msdn about this:
Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> Delegate
But how do I pass different type parameter and different number of parameters?
答案 0 :(得分:8)
The easiest way is by not passing the parameters in at all and instead doing variable capture.
public T GetOrAdd<T>(string key, Func<T> builder)
{
var result = _someCache.Get<T>(key);
if(result != null)
return result;
result = builder();
_someCache.Add(key, result);
return result;
}
used like
var address = myCache.GetOrAdd<Address>(AddressKeyBuilder(para1, para2),
() => Addressrepository.GetAddress(para1, para2)
);
This is the same pattern ConcurrentDictionary uses for it's GetOrAdd method.