ASP.NET Core依赖注入错误:无法解析StackExchange.Redis.IDatabase类型的服务
我正在开发一个ASP.NET Core Web API,并使用Redis(StackExchange.Redis)来进行速率限制。Redis正在通过Docker Desktop运行,容器已经启动并可在 localhost:6379 访问。
然而,当我启动应用时,启动阶段因依赖注入错误而失败,错误信息为 IDatabase。
System.AggregateException: 某些服务无法被构造(在验证服务描述符 'ServiceType: SmartApiSystem.API.Services.RateLimiterService Lifetime: Scoped ImplementationType: SmartApiSystem.API.Services.RateLimiterService': Unable to resolve service for type 'StackExchange.Redis.IDatabase' while attempting to activate 'SmartApiSystem.API.Services.RateLimiterService'.)
错误提示: 在尝试激活
RateLimiterService时,无法解析类型StackExchange.Redis.IDatabase的服务
Program.cs
using SmartApiSystem.API.Services;
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
// Redis (advanced usage)
builder.Services.AddSingleton<IConnectionMultiplexer>(
ConnectionMultiplexer.Connect("localhost:6379"));
// Redis (simple caching)
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});
RateLimiterService.cs
using StackExchange.Redis;
namespace SmartApiSystem.API.Services
{
public class RateLimiterService
{
private readonly IDatabase _db;
public RateLimiterService(IDatabase database)
{
_db = database;
}
public async Task<string> CheckLimitAsync(string user)
{
string key = $"rate:{user}";
var count = await _db.StringIncrementAsync(key);
if (count == 1)
await _db.KeyExpireAsync(key, TimeSpan.FromMinutes(1));
if (count > 5)
return "Rate limit exceeded";
return $"Request allowed Count: {count}";
}
}
}
解决方案
替代方案:在DI容器中不注册 IDatabase 服务。
-
在你的
RateLimiterService(或任何使用Redis的服务)的构造函数中,从DI容器获取IConnectionMultiplexer服务,而不是获取IDatabase服务。 -
通过
redis.GetDatabase()获取IDatabase服务实例。
public class RateLimiterService
{
private readonly IDatabase _db;
public RateLimiterService(IConnectionMultiplexer redis)
{
_db = redis.GetDatabase();
}
...
}
参考: .NET与 Redis入门教程:StackExchange.Redis Getting Started Guide