Using MethodBase, is it possible to get the parameters and their values of the method that’s being called?
To be specific, I’m trying to use reflection to create Cache keys. As each method and its parameter list is unique, I thought it’d be ideal to use this as the key. This is what I’m doing:
public List<Company> GetCompanies(string city)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCity(city);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
public List<Company> GetCompanies(string city, int size)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCityAndSize(city, size);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
Where GetCacheKey() is defined (roughly) as:
public string GetCacheKey()
{
StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
string name = methodBase.DeclaringType.FullName;
// get values of each parameter and append to a string
string parameterVals = // How can I get the param values?
return name + parameterVals;
}
Why do you want to use reflection? In the place where you use your
GetCacheKeymethod you know the values of the parameters. You can just specify them:And use like this: