我有ASP.Net Core 2.1
应用。需要使用RedisCache
作为缓存。
这是我的方法向缓存添加项目的外观。
public class RedisCache : ICache<Customer> //custom interface
{
#region Private
private readonly IConfiguration _configuration;
private readonly IDatabase _cache;
private readonly ConnectionMultiplexer _connection;
private readonly IRedisTypedClient<Customer> _redisClient;
#endregion Private
#region Ctor
public RedisCache(IConfiguration configuration, IRedisTypedClient<Customer> redisClient)
{
_configuration = configuration;
_connection = ConnectionMultiplexer.Connect(configuration.GetSection("AWS:Cache")["Redis:Server"]);
_cache = _connection.GetDatabase();
_redisClient = redisClient;
}
#endregion Ctor
public async Task<Customer> AddItem(Customer item)
{
try
{
await Task.Run(() => _redisClient.GetAndSetValue(item.Id, item)).ConfigureAwait(false);
return item;
}
catch (Exception ex)
{
Logger.Log(ex, item);
return null;
}
}
}
依赖关系注册
services.AddScoped<IRedisTypedClient<Customer>>(); //DI Registration
当应用运行时,它引发错误
无法解析'ServiceStack.Redis.Generic.IRedisTypedClient类型的服务
因此尝试将DI注册为
services.AddScoped<IRedisTypedClient<Customer>>(di => new RedisTypedClient);
但是没有找到这样的东西,编译器也不会抛出构建错误。
如何注册此IRedisTypedClient
依赖项?
谢谢!
最后一部分代码更接近您的需求,但是很明显为什么会引发编译时错误。您没有包括泛型类型参数,并且缺少括号,即使那样,该类型几乎肯定也必须在构造函数中接受一些您没有提供的参数。它应该看起来像:
services.AddScoped<IRedisTypedClient<Customer>>(p =>
{
// Use `p` to get services, config values etc. For example:
// var config = p.GetRequiredService<IConfiguration>();
return new RedisTypedClient<Customer>(someParam);
}
就是说,对于缓存,您不应该直接使用Redis。您应该先注入IDistributedCache
,然后再包含Redis cache provider:
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});