I am currently building cache for my application, and I would like to have my redis cache client work the same way you would dependency inject a DbContext.
I am using StackExchange.Redis to manage my redis cache: https://github.com/StackExchange/StackExchange.Redis
I have made it work, but I am not very confident in the way I implemented it.
In my services I have added:
services.AddSingleton<IConnectionMultiplexer(ConnectionMultiplexer
.Connect("localhost:6379,allowAdmin=true"));
services.AddScoped<ICacheClient, CacheClient>();
I could not figure out how to add IDatabase to services.
My CacheClient looks like this:
public class CacheClient : ICacheClient
{
private readonly IConnectionMultiplexer _connectionMultiplexer;
private readonly IDatabase _redisCache;
private readonly ISerializer _serializer;
public CacheClient(IConnectionMultiplexer connectionMultiplexer, ISerializer serializer)
{
_connectionMultiplexer = connectionMultiplexer;
_serializer = serializer;
_redisCache = connectionMultiplexer.GetDatabase();
}
//add/set cache methods removed for the sake of brevity.
}
From here I can use _redisCache to access the database and do operations such as _redisCache.StringSetAsync etc...
Now ICacheClient can be injected into my application and I can use my cache logic in any class. Which is very nice.
Is there anything wrong with this way of implementing my cache client?