If I have an inline expression, will all references to that expression be the same for the lifetime of an application?

45 views Asked by At

So I have some code that filters a foo by primary key and applies a transformation

public T GetFooByIdAndApplyTransformation<T>(int fooID, func<Foo,T> transformation)
{
         return dbContext.Foo
                    .Where(x => x.id == fooID)
                    .Select(x => transformation(x))
                    .FirstOrDefault()

}

Presumably it would be called like so

  var fooBarId = GetFooByIdAndApplyTransformation(fooId, (x) => x.BarId)

I would like to set it up so that the result could conceivably be cacheable so that I'm not hitting the database. The primary goal of that is I need to cache on both the ID and the transformation; so I'd update the function to be

public T GetFooByIdAndApplyTransformation<T>(int fooID, func<Foo,T> transformation, bool Cacheable = false)
{
    T result;
    var cacheKey = new Tuple(fooId, transformation)
    
    if (Cacheable && Cache.TryGet(cacheKey, out var cacheResult))
    {
        result = (cacheResult as T) ?? throw new InvalidOperationException($"Cached value cannot be cast to type {T.GetType()}")
    }
    else
    {
        result = dbContext.Foo
               .Where(x => x.id == fooID)
               .Select(x => transformation(x))
               .FirstOrDefault()
        if (Cachable) {
            cache.Set(cacheKey, result)
        }
    }
    return result
}

I am aware that this has some limitations; not maybe not every query should be cached so I added an optional parameter to set caching; even if I have functionally identical expression at two separate points in my code it would still be two difference references so I would in effect I could have two sets of keys in the cache pointing to the same value.

That said, if a singular anonymous function would be guaranteed to have the same reference for the lifetime of an application that'd be my first start to having centralized caching solutions. I could resolve the issue of logically identical expressions by abstracting them to an actual named function and I'd be on my way to having centralized caching of my cacheable queries (currently each query caller does some version of it's own caching, some done well, some not done so well which is what I'm trying to fix)

0

There are 0 answers