Created
December 11, 2014 07:47
-
-
Save Imater/a1d99a2ba736eb8de835 to your computer and use it in GitHub Desktop.
Cache for all queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
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