Search code examples
cachingspring.netspring-aopspring-el

Spring.Caching.AspNetCache - Condition based on ReturnValue - Condition in Spring Expression Language


I use Cache Aspect with ASP.NET Cache. I need create condition based on ReturnValue.

I simplified my problem. I use CacheResult aspect on method wich return simple POCO object.

Here is definition:

public class MyData
{
    public string MyProperty { get; set; }
}

public class MyResponse
{
    public int MyId { get; set; }
    public MyData [] Result { get; set; }
}

I need create condition for cache - Cache result only if MyResponse.MyData.Lenght is bigger then batch limit.

[CacheResult("AspNetCache", "'MyResponse.MyId=' + #id", 
             Condition = "MyResponse.Result.Length > #batchLimit")]
public MyResponse GetResponse(int id, int batchLimit)
{
    Thread.Sleep(5000);
    return new MyResponse
               {
                   MyId = 1,
                   Result =
                       new MyData[]
                           {
                               new MyData {MyProperty = "A"}, new MyData {MyProperty = "B"},
                               new MyData {MyProperty = "C"},
                           }
               };
}

I tried this definition of condition:

Condition = "MyResponse.Result.Length > #batchLimit"

I got this error:

'MyResponse' node cannot be resolved for the specified context [Sample.MyResponse].

So I tried second version:

Condition = "'MyResponse.Result.Length' > #batchLimit"

Finished with error:

Cannot compare instances of [System.String] and [System.Int32] because they cannot be coerced to the same type.

I google it I can use keyword ReturnValue something like this:

Condition = "#ReturnValue != null"

But I don't know how I can access to MyResponse.MyData.Length.


Solution

  • the context for the evaluation of the condition expression is the return value, so just do this:

    Condition = "Result.Length > #batchLimit"
    

    equivalent to

    Condition = "#root.Result.Length > #batchLimit"