Skip to content

Instantly share code, notes, and snippets.

@Imater
Created December 12, 2014 09:57
Show Gist options
  • Save Imater/d337d28e52db34f906be to your computer and use it in GitHub Desktop.
Save Imater/d337d28e52db34f906be to your computer and use it in GitHub Desktop.
cache
//Install-Package Newtonsoft.Json -ProjectName Ksnsi.Queries
//Install-Package MemoryCache -ProjectName Ksnsi.Queries
using System;
using MemoryCache;
using Newtonsoft.Json;
namespace Ksnsi.Queries
{
public interface IQueryProcessor
{
TResponse Process<TResponse, TContext>(TContext queryContext)
where TContext : IQueryContext<TResponse>;
}
public class QueryProcessor : IQueryProcessor
{
private readonly Func<Type, Type, object> _func;
public QueryProcessor(Func<Type, Type, object> func)
{
_func = func;
}
#region IQueryProcessor Members
public TResponse Process<TResponse, TQueryContext>(TQueryContext queryContext)
where TQueryContext : IQueryContext<TResponse>
{
string key = queryContext.GetType() + JsonConvert.SerializeObject(queryContext);
if (Cache.Exists(key))
{
var obj = Cache.Get(key);
return (TResponse)obj;
}
var q = (IQuery<TQueryContext, TResponse>)_func(typeof(TQueryContext), typeof(TResponse));
var response = q.Execute(queryContext);
if (!(response == null))
{
Cache.Store(key, response);
}
return response;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment