Reputation: 1172
I have quite an unnecessary dilemma. I'm lazily looking for a function that would convert a lamda expression into a string. It bothers me that I'm typing in this cache key every time but I don't really want to take the time to create it.
I want to use it for a cache function I created:
Where if I wanted to get a name for a person without calling the function every time.
public static string GetPersonName(int id)
{
return Repository.PersonProvider.Cached(x => x.GetById(id)).Name;
}
The GetExpressionDescription would return "PersonProvider.GetById(int 10)"
I figure this is possible but I wonder if anyone has already built this or has seen it somewhere.
public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, double hours = 24)
{
var expressionDescription = GetExpressionDescription(function);
return Cached(function, expressionDescription, hours);
}
public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, string cacheName, double hours = 24)
{
var context = HttpContext.Current;
if (context == null)
return function.Compile().Invoke(obj);
R results = default(R);
try { results = (R)context.Cache[cacheName]; }
catch { }
if (results == null)
{
results = function.Compile().Invoke(obj);
if (results != null)
{
context.Cache.Add(cacheName, results, null, DateTime.Now.AddHours(hours),
Cache.NoSlidingExpiration,
CacheItemPriority.Default, null);
}
}
return results;
}
Upvotes: 6
Views: 11405
Reputation: 112259
You can simply get a string representation of an Expression<>
with .ToString()
:
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
Test(s => s.StartsWith("A"));
}
static void Test(Expression<Func<string,bool>> expr)
{
Console.WriteLine(expr.ToString());
Console.ReadKey();
}
}
Prints:
s => s.StartsWith("A")
See: https://dotnetfiddle.net/CJwAE5
But of course it will not yield you the caller and the values of variables, just the expression itself.
Upvotes: 7
Reputation: 1430
Maybe you should try DynamicExpresso. I used that library to develop a lightweight business-rules engine.
https://github.com/davideicardi/DynamicExpresso
Upvotes: 3