Store / Load generic types in Redis with C#

Asked

Viewed 133 times

1

Setting

I created a function using AOP to cache information, when the method is called I store in Redis using the cache.StringSet, but when I need to capture back the value of Redis I need it to come back of the same type that I received, I don’t know if I’m doing it right Saving and storing the string, but when I return from Redis cache.StringGet I need it to be the same type when the object was inserted. Remembering that objects can vary, they can be of N different types.

Code

public sealed override void OnInvoke(MethodInterceptionArgs args)
{
    var cache = RedisConnectorHelper.Connection.GetDatabase();
    var result = cache.StringGet(args.Method.Name);

    if (result.HasValue)
    {
        args.ReturnValue = result;
        return;
    }

    base.OnInvoke(args);
    cache.StringSet(args.Method.Name, Serialize(args.ReturnValue));
}

private string Serialize(object obj)
{
    return JsonConvert.SerializeObject(obj);
}

1 answer

2


I bypassed the problem with the following solution:

In the input method where I have Aspect I changed the types to dynamic. So the input and output is generic, using object also worked. For now I’ll keep it that way.

[RedisCacheableResult]
public List<dynamic> ReturnCustomer()
{
    var lstCustomer = new List<dynamic>();

    var customer = new Customer
    {
        Id = 1,
        Name = "Acme Inc",
        Email = "[email protected]"
    };

    var customer1 = new Customer
    {
        Id = 2,
        Name = "Marvel Inc",
        Email = "[email protected]"
    };

    lstCustomer.Add(customer);
    lstCustomer.Add(customer1);

    return lstCustomer;
}

In Deserialize I use:

private static dynamic Deserialize(string data)
{
    return JsonConvert.DeserializeObject<List<dynamic>>(data, Settings);
}

Follows the solution published in Github: https://github.com/thiagoloureiro/TestaCache

Issues, pullrequests, Stars and Forks are welcome :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.