I have an ASP.NET Core Project ( Aspect-Oriented ) with In-Memory Cache and I use IMemoryCache interface for it.
I want to convert this to Redis caching...
But I noticed that In-Memory caching with IMemoryCache can keep data as "object" type.
public void Add(string key, object data, int duration)
{
_cache.Set(key, data, TimeSpan.FromMinutes(duration));
}
And when I get the value, it can bring it as object...
public object Get(string key)
{
var keyValue = _cache.Get(key); //Get method returns as string
return keyValue;
}
SO , I can get the value from cache as the type of it and return it...
And when I convert it to RedisCacheManager ;
public static string ToJson(this object value)
{
var aa = JsonConvert.SerializeObject(value, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return aa;
}
SET
public void Set(string key, object value, int duration)
{
var k = value.ToJson();
_client.GetDatabase().StringSet(key, k, TimeSpan.FromMinutes(duration));
}
GET
public object Get(string key)
{
var keyValue = _client.GetDatabase().StringGet(key); //returns as "RedisValue" type
return keyValue;
}
this returns as "RedisValue"
and while using In-Memory cache with IMemoryCache, value returns as object and would be cast to its own type (for example as "List-Product" or "List-Category" ....)
So I wasn't touching anything in that process but when I use Redis, value returns as RedisValue then it returns this value
SO I GOT AN ERROR about Casting the value to whatever I need , But I use Interceptor and don't specify the type of it..
public class CacheAspect : MethodInterception
{
private int _duration;
private IRedisCacheService _cacheManager;
public CacheAspect(int duration = 60)//Default
{
_duration = duration;
_cacheManager = ServiceTool.ServiceProvider.GetService<IRedisCacheService>();
}
public override void Intercept(IInvocation invocation)
{
var methodName = string.Format($"{invocation.Method.ReflectedType.FullName}.{invocation.Method.Name}");
var arguments = invocation.Arguments.ToList();
var key = $"{methodName}({string.Join(",", arguments.Select(x => x != null ? JsonConvert.SerializeObject(x, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }) : "<Null>"))})";
if (_cacheManager.IsAdd(key))
{
var cacheValue = _cacheManager.Get(key); //returns as object
return;
}
invocation.Proceed();
_cacheManager.Set(key, invocation.ReturnValue, _duration);
}
}
Is there ANYONE who has encountered with this situation or what can I do to deal with this ??