首页 > 解决方案 > 无法解析类型“Microsoft.AspNetCore.DataProtection.IDataProtector”的服务

问题描述

我有一个自定义服务,我正在使用 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);

标签: c#asp.net-coredependency-injection

解决方案


最后,我发现了问题:

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


推荐阅读