gpt4 book ai didi

c# - 无法解析 ASP.Net Core 中类型“ServiceStack.Redis.Generic.IRedisTypedClient”的服务

转载 作者:行者123 更新时间:2023-12-03 01:00:20 25 4
gpt4 key购买 nike

我有 ASP.Net Core 2.1 应用程序。需要使用RedisCache作为Cache。

这就是我的方法将项目添加到缓存的方式。

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

当应用程序运行时,它会抛出错误

Unable to resolve service for type '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。您应该注入(inject) IDistributedCache 然后包含 Redis cache provider :

services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});

关于c# - 无法解析 ASP.Net Core 中类型“ServiceStack.Redis.Generic.IRedisTypedClient”的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com