【发布时间】:2021-10-29 11:19:15
【问题描述】:
我收到了这个 DI 错误,虽然我已经阅读了其他有同样错误的帖子,但还不足以找到导致这个错误的原因:
System.InvalidOperationException:尝试激活“WatsonConnection.Controllers.CacheManagementController”时无法解析“WatsonConnection.Interfaces.ICacheManagement”类型的服务。
startup.cs 中的配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICacheManagement, CacheManagementService>();
services.AddSingleton<IConnectionMultiplexer>(
ConnectionMultiplexer.Connect(Configuration["Redis:ConnectionString"])
);
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = Configuration["Redis:ConnectionString"];
});
services.AddHttpContextAccessor();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WatsonConnector", Version = "v1" });
});
}
这是我正在尝试实现服务的控制器:
public class CacheManagementController : ControllerBase
{
ICacheManagement cacheManagement;
public CacheManagementController(ICacheManagement _cacheMgmt)
{
this.cacheManagement = _cacheMgmt;
}
[HttpGet("CachedKeys")]
public IActionResult GetListCacheKeys([FromQuery][DefaultValue("*")] string pattern)
{
return Ok(cacheManagement.GetListCacheKeys(pattern));
}
}
服务实现:
public class CacheManagementService : ICacheManagement
{
private IConnectionMultiplexer multiplexer;
private ICacheManagement cache;
public CacheManagementService(IConnectionMultiplexer multiplexer)
{
this.multiplexer = multiplexer;
}
public IEnumerable<RedisKey> GetListCacheKeys([DefaultValue("*"), FromQuery] string pattern)
{
var keys = multiplexer
.GetServer(multiplexer
.GetEndPoints()
.First())
.Keys(pattern: pattern ?? "*").ToArray();
return keys;
}
}
这是界面:
public interface ICacheManagement
{
IEnumerable<RedisKey> GetListCacheKeys([FromQuery][DefaultValue("*")] string pattern);
}
正如我所见,我已经在配置服务中指定了单例以明确地将服务与接口配对,但这还不够,有什么想法吗?
【问题讨论】:
-
您能分享一下您是如何在配置服务中注册单例对的吗?
-
@AnthonySerranoBianco services.AddSingleton
();我已经在问题中粘贴了配置服务 -
@GabrielManzini 检查您的整个对象图,并确保所有必要的依赖项都已注册到容器中,以便可以解决它们。
-
根据当前显示的代码,问题可能与
IConnectionMultiplexer实现有关。 -
此 API 与另一个 API 在同一个解决方案中,单独启动此 API 即可解决问题
标签: c# asp.net asp.net-core dependency-injection redis