从 Startup net core 在服务中注入两个依赖项 Iconfiguration 和 IMemoryCache 时出错

Error injecting two dependencies Iconfiguration and IMemoryCache in service from Startup net core

我尝试在服务中使用 IMemoryCache 而不是使用 Iconfiguration,但实际上我不知道在构造函数中注入的正确方法。

服务:

 public class AuthService: IAuthService
 {
    private readonly IConfiguration _configuration;
    private readonly IMemoryCache _cache;

    public AuthService(IConfiguration configuration, IMemoryCache cache)
    {
        _configuration= configuration;
        _cache = cache;
    }
 }

*在启动中以单例方式注入(错误:使用该服务使用任何控制器时生成错误):

  services.AddMemoryCache();
  services.AddSingleton<AuthService>();

*在启动时注入创建 class 服务(错误:构造函数需要 IMemoryCache

services.AddMemoryCache();
services.AddSingleton<IAuthService>(
         new AuthService(Configuration)
);

从启动中将 IMemoryCache 注入 AuthService 的正确方法是什么 class?

services.AddMemoryCache()register 实例作为单例,这意味着没有不匹配的生命周期。

另外,不需要手动指定工厂。正如 Jesse 上面提到的,注册你的接口和具体 class 依赖注入框架将为你的服务提供这两种依赖:

services.AddSingleton<IAuthService, AuthService>();