Store / Load generic types in Redis with C #

1

Scenery

I created a function using AOP to do information cache, when the method is called I store in Redis using cache.StringSet , but when I need to capture back the value of Redis I need to return the same type as I received, I know if I'm doing the right thing by serializing and storing the string, but when I get back 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);
}
    
asked by anonymous 11.12.2017 / 19:32

1 answer

2

I circumvented the problem with the following solution:

In the input method where I have the 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;
}

No Deserialize I use:

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

Follow the solution published in GitHub : link

Issues, pullrequests, stars and forks are welcome:)

    
13.12.2017 / 10:59