Stavo cercando Caching nella mia web api dove posso usare l'output di un metodo api (che cambia una volta in 12 ore) per chiamate secondarie e poi ho trovato this solution su SO, ma sto avendo una difficoltà nella comprensione e usando il codice seguenteMemory Cache in web api
private IEnumerable<TEntity> GetFromCache<TEntity>(string key, Func<IEnumerable<TEntity>> valueFactory) where TEntity : class
{
ObjectCache cache = MemoryCache.Default;
var newValue = new Lazy<IEnumerable<TEntity>>(valueFactory);
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30) };
//The line below returns existing item or adds the new value if it doesn't exist
var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<IEnumerable<TEntity>>;
return (value ?? newValue).Value; // Lazy<T> handles the locking itself
}
non sono sicuro di come chiamare e utilizzare questo metodo nel contesto di seguito? Ho un metodo Get
public IEnumerable<Employee> Get()
{
return repository.GetEmployees().OrderBy(c => c.EmpId);
}
e voglio mettere in cache l'output di Get e utilizzarlo in altri miei metodi GetEmployeeById() o Search()
public Movie GetEmployeeById(int EmpId)
{
//Search Employee in Cached Get
}
public IEnumerable<Employee> GetEmployeeBySearchString(string searchstr)
{
//Search in Cached Get
}
@little è fatto all'interno del metodo GetFromCache –
@little si dovrebbe chiamare il repository all'interno della funzione valueFactory (verrà eseguito solo se l'oggetto non è in il cache). Guarda la mia risposta non sto chiamando un repository ma direttamente il contesto, quindi sostituisci il contesto con il repository. –
@little ho aggiornato il metodo GetMovieBySearchParameter nel mio esempio e ora sta utilizzando un repository. –