【问题标题】:Unable to resolve service for type 'Microsoft.AspNetCore.DataProtection.IDataProtector'无法解析类型“Microsoft.AspNetCore.DataProtection.IDataProtector”的服务
【发布时间】:2020-08-01 11:27:14
【问题描述】:

我有一个自定义服务,我使用的是 Microsoft 的 IDataProtector。 我在启动时使用AddScoped 注册了我的服务,但我在使用IDataProtector 时遇到了问题。

错误信息:

在尝试激活“服务”时无法解析“Microsoft.AspNetCore.DataProtection.IDataProtector”类型的服务。

这是我的代码:

public class Service: IInjectable
{
    private readonly IDataProtector _protector;
     
    public Service(IDataProtector protector)
    {
      _protector = protector.CreateProtector("key");
    }

    other code ...
}

我注册服务的方式:

    public static void RegisterScoped<T>(
        this IServiceCollection services, params Assembly[] assemblies)
    {
        IEnumerable<Type> types = assemblies.SelectMany(a => a.GetExportedTypes())
            .Where(c => c.IsClass && typeof(T).IsAssignableFrom(c));

        foreach (var item in types)
            services.AddScoped(item);
    }

启动:

 services.RegisterScoped<IInjectable>(typeof(IInjectable).Assembly);

【问题讨论】:

  • services.AddDataProtection(); ?
  • @viveknuna 我有几个服务,因为我没有一一添加
  • @GuruStron 没用 :(
  • @GuruStron 是的,你是对的,我误解了这个问题
  • @user13409315 还没有解决?可以加minimal reproducible example吗?

标签: c# asp.net-core dependency-injection


【解决方案1】:

终于找到问题了:

我必须在我的服务构造函数中使用 IDataProtectionProvider 而不是 IDataProtector

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2022-01-10
    • 2020-03-13
    • 2019-02-10
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多